问答

Typescript中多类型判断该怎么写?

作者:admin 2021-04-19 我要评论

假设有以下四个interface interface A{ a:string}interface B{ b: string}interface C{ c: string }type ObjectType = A|B|Cconst test:ObjectType = {a: '1'}//...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

假设有以下四个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)
  }
}

这样?

###

image.png
当然我例子是在同一个位置写的啊,你的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 相关事件
}

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • nginx响应速度很慢

    nginx响应速度很慢

  • 点击选中的多选框,会在已选那一栏显示

    点击选中的多选框,会在已选那一栏显示

  • PHP 多态的理解

    PHP 多态的理解

  • 关于C语言中static的问题

    关于C语言中static的问题

腾讯云代理商
海外云服务器