假设有以下四个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|C
function fun(test: ObjectType) {
if (is<A>(test, 'a')) {
console.log(test.a)
} else if (is<B>(test, 'b')) {
console.log(test.b)
} else if (is<C>(test, 'c')) {
console.log(test.c)
}
}
这样?
###
当然我例子是在同一个位置写的啊,你的interface肯定是写在d.ts的声明里面的,然后testA这几个就是写在你要判断的位置,然后你看看能不能帮你识别出来深层以后这个类型。希望能帮到你吧,也不是很确定,不过感觉不太会出现追不到类型的情况
自己再做一点补充,根据 @zzgzzg00 的思路,利用in
和单独属性进行判断。
问题中A、B、C的单独属性分别是a、b、c
if('a' in test){
// 执行 A 相关事件
}else if('b' in test){
// 执行 B 相关事件
}else if('c' in test){
// 执行 C 相关事件
}