假设有以下四个interface
interface A{
a:string
}
interface B{
b: string
}
interface C{
c: string
}
type ObjectType = A|B|C
const test:ObjectType = {a: '1'}
// if(test.b){
//
// }
在当前文件里,会提示b不存在A中。但是隔了多个文件,比如React中从父组件传递到子组件中,就无法判断test到底是A、B、C。这个时候要怎么写才能判断?
if(test 是 A类型){
// 执行 A 相关事件
}else if(test 是 B类型){
// 执行 B 相关事件
}else if(test 是 C类型){
// 执行 C 相关事件
}
判断语句该如何书写?
回答:
function is<T extends object>(v: any, k: string): v is T {return k in v;}interface A {a: string}interface B {b: string}interface C {c: string}type ObjectType = A | B | Cfunction fun(test: ObjectType) {if (is(test, ‘a’)) {console.log(test.a)} else if (is(test, ‘b’)) {console.log(test.b)} else if (is < C > (test, ‘c’)) {console.log(test.c)}}
本文地址:H5W3 » Typescript多类型判断该怎么写?