You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typeCar={id: number;car: string;};typeBike={id: string;bike: string;};typeVehicle=Car|Bike;constgetVal=(val: Vehicle)=>{if(typeofval.id==='number'){returnval.car;}};// 这种情况是不能够达到目的的,会报错// Property 'car' does not exist on type 'Vehicle'.// Property 'car' does not exist on type 'Bike'.ts(2339)
那你想要通过对应的唯一属性判断也是不行的
constgetVal=(val: Vehicle)=>{if(typeofval.id==='number'){returnval.car;}if(val.car){returnval.car;}};// 同样的报错// Property 'car' does not exist on type 'Vehicle'.// Property 'car' does not exist on type 'Bike'.ts(2339)
类型判断
typeof
处理一些基础类型的数据
string | number | bigint | boolean | symbol | undefined | object | function
不能检测更复杂的数据类型,例如
array
也不适合对于对象的属性进行判断(常见的使用误区)
那你想要通过对应的唯一属性判断也是不行的
如果非要使用
typdof
来判断的的话,只能添加类似type
的属性来区分这样才能通过类型检查,其实就没有必要了
属性或方法判断
in
通过
in
方法来区分对象就方便的多这样就可以直接使用
Car
下的属性(不仅仅是代码中的car
属性)实例判断
instanceof
用的不多,用于判断类的实例
The text was updated successfully, but these errors were encountered: