首先typeof能返回的所有数值有
string
number
bigint
boolean
symbol
undefined
object
function
无法返回或者说是识别的情况有
Array[] -> object
Object{} -> object
Date -> object
null -> object
所以在TypeScript可以使用instanceof来判断类型
instanceof
if(a instanceof Date){}
instanceof的缺点在于无法识别 string 和 number 还有 boolean
在使用中可以混合使用typeof 与 instanceof
const f =(a:Date | string | Date[]) => {
if(typeof a === 'string'){}
else if(a instanceof Date){}
else {}
}
因为js有类型擦除 所以在有多个数据需要判断的时候可以使用in来判断
type Person = { username: 'frank'}
type Animal = { petname : 'bobby' }
const f = (a: Person | Animal) => {
if('username' in a){}
else if('petname' in a){}
}
以上都是用javescript来实现的判断
在Typescript中可以使用is 优点 : 支持所有的ts类型 缺点 : 语法复杂麻烦
type Rect = {
height: number
width: number
}
type Circle = {
center:[number, number]
radius: number
}
const f = (a: Rect | Circle) =>{
if(isCircle(a)){ }
}
function isCircle(x: Rect | Circle) : x is Circle {
return 'center' in x && 'radius' in x
}
第二种方法就是在类型中增加辨别
type Circle = {kind: 'Circle', center:[number,number]} // kind 则为添加的识别
type Square = {kind: 'Square', sideLength: number} // kind 当然也可以取别的名字e.g cate type kind
type Shape = Circle | Square
const f = (a:string | number | Shape) => {
if(a.kind === 'Circle'){}
else if(typeof a === 'string'){}
}