ts 之 多种泛型的处理方式

  最近在使用ts写程序,以前碰到了类型问题基本都用any大法解决了。但是这样是不符合规范的,最近时间较多可以真正对多种类型的问题进行一次总结。

  

  需要注意的是,当某个变量类型声明2种或以上时,我们只能使用这几种类型共有的方法,否则会报错。

  

function demo(demo1: string | any[]) {
    console.log(demo1.length); // 0
    console.log(demo1.concat([1,2,3])); // Argument of type 'number[]' is not assignable to parameter of type 'string'
}

  如上所示,demo1.length由于string类型和数组类型都会有这个属性,所以是正常的。但是由于demo1暂时无法确定是什么什么类型,且concat是属于数组的方法,故而ts会报错。

  解决这种问题的方法很简单。js判断一下类型就可以了。

function demo(demo1: string | any[]) {
    console.log(demo1.length);
    if(typeof demo1 === 'string') return;
    console.log(demo1.concat([1,2,3]));
}

  这样还有一个问题,如果我们定义了两个自定义类型那么又该怎么办呢?

  

interface interdemo1 {
    name: string
    age: string
}
interface interdemo2 {
    name: string
    cname: string
}
function demo(demo1: interdemo1 | interdemo2) {
    console.log(demo1.name);
    if((<interdemo1>demo1).age) {
        console.log((<interdemo1>demo1).age);
    }
}

  使用ts的类型保护,可以保证类型的前提下并且不影响其运行,还是很方便的。

  详情可见 https://www.tslang.cn/docs/handbook/advanced-types.html

  

原文地址:https://www.cnblogs.com/acefeng/p/13987588.html