Skip to content

base_TS_API

TS中的一些api使用方式

类型推断

ts
let tempString:string="guluwater.com";
tempString="咕噜水";//可以赋值
tempString=123//数字其他的类型无法赋值

数组:
let tempArr:(string | boolean | number)[]=["guluwater.com",66,false];//数组中包含 字符串 布尔值 数组 此三类可被添加入数组
tempArr.push("咕噜"88true);

对象:
let tempObject={name:"guluwater",year:2024,open:true,lesson:[{title:"TS"}]}//根据类型使用对象中的值不然会报错
tempObject.open="11";//此时会报错
tempObject.lesson.push({title:"linux"})

> 手动限定类型的值
let gulu:{name:string;age:number;url?:string}
gulu={name:"guluwater",age:2024}//正常无报错
gulu={name:11,age:2024};//报错

其他类型说明

INFO

any类型不做校验

unknown是不知道什么类型 但是将字符串复制给string类型会报错

tsx
let gulu:any="guluwater.com";
let a:string=gulu;//不报错

let gulu:unknown="guluwater.com";
let b:string=gulu;//报错

断言
let gulu:string='99';
let c:number=hd as unknown as number;//不报错

INFO

void:不返回具体的值 一般返回null或者undefined;

never 不会执行到底 返回错误

tsx
let gulu:void = undefined;
gulu=null//不报错
一般用在函数上-不返回具体的类型 返回具体的类型会报错
function gulu():void{
}

never 不会执行到底 返回错误
function gulu():never{
    throw new Error("类型错误")
}

INFO

null 和undefined

tsx
let gulu:null=null;
let extragulu:undefined=undefined;
console.log(gulu,extragulu)//不报错
 function get():null|string{
     return null
 }
console.log(get())//不报错

INFO

Function 函数申明是大写开头

tsx
let gulu:Fuction
gulu=()=> "guluwater.com"

INFO

使用type对函数参数进行声明:

tsx
let addUser =(user:{name:string,age:number}):void =>{

​	console.log("添加用户")

}

addUser ({name:'guluwater;,age:18})

let updateUser = (user:{name:string,age:number}) :void=>{

​	console.log("更新用户")

}

updateUser ({name:'guluwater;,age:18})

使用type定义:

tsx
type userType={name:'guluwater;,age:18,sex?:string|number}
let addUser =(user:userType):void =>{

​	console.log("添加用户")

}

addUser ({name:'guluwater;,age:18})

let updateUser = (user:userType) :void=>{

​	console.log("更新用户")

}

updateUser ({name:'guluwater;,age:18,sex:'1'})
tsx
剩余参数
function sum(...args:number[]):number{
    return args.reduce((s,n)=>s+n,0)
}
console.log(sum(1,2,3,4))

function push(arr:any[],...args:any[]):any[]{
    arr.push(...args)
    return arr
}
let gulu=["guluwater"]
push(gulu,"aa",'bb')

元祖(tuple)
let arr:(string|number|boolean)[]=['guluwater',88,false];
arr[0]=false;
console.log(arr)//不报错

位置固定
let tuple:(string|number|boolean)[]=['guluwater',88,false];
tuple[0]=false;
console.log(tuple)//报错

2024 Alvisliu. All Rights Reserved.