TS可以进行哪些类型操作?
- 联合类型,求并集 type A = number type B = string type C = A | B // 使用“|”来求类型A和类型B的并集 结果是 number|string
- 求交集 type A = number type B = string type C = A & B // 使用“&”来求类型A和类型B的交集 结果是空集 never
进行类型收窄时可以使用哪些方法来收窄类型?
- typeof 来判断一个值的基本类型
- instansof 来判断一个对象是数组还是函数
- 使用in操作符来判断,对象上是否包含某个key
- 使用类型谓词is来进行判断
- 使用kind属性(给每个类型添加一个的字段kind,根据kind的值来判断类型)
type Rect={
height:number
width:number
}
type Circle={
center:[number,number],
redius: number
}
const f=(a:Rect|Circle)=>{
if(isRect(a)){
console.log(a.height,a.width,)
}else if(isCircle(a)){
console.log(a.center,a.redius)
}else{
throw Error('参数错误')
}
}
// 使用is关键字来告诉TS我返回的boolean表示的类型
const isRect=(a:Rect|Circle):a is Rect=>{
return 'height' in a && "width" in a
}
const isCircle=(a:Rect|Circle):a is Circle=>{
return 'center' in a && "redius" in a
}
f({height:59,width:50})
export {}
函数重载是什么?
函数重载: 同名函数.
- 解决一个函数接受不同类型的参数. 对于TS来说,可以使用联合类型,然后类型收窄.
- 一个函数接受不同类型的参数和不同数量的参数(建议改名字,写成两个函数,避免函数重载) 也可以使用联合类型,比较繁琐.这时候一般使用函数重载
- 写法
// 函数重载
function createDate(n:number):Date
function createDate(year:number,month:number,date:number):Date
function createDate(a:number,b?:number,c?:number):Date{
if(a!==undefined && b!==undefined && c!==undefined){
return new Date(a,b,c)
}else if(
a!==undefined && b===undefined && c===undefined
){
return new Date(a)
}else{
throw new Error('参数错误')
}
}
createDate(1000000)
createDate(2022,0,1)
as const 是什么意思?
类型推导 当我们使用const定义一个值的时候,类型系统会自动推导这个值就是类型 as const 是我们告诉TS 往具体的推导
const arr=[1,"h1"] // (string | number)[]
const arr=[1,"h1"] as const // readonly [1, 'h1']