【问题标题】:Variable as Interface or Interface[] type作为 Interface 或 Interface[] 类型的变量
【发布时间】:2020-03-03 23:44:10
【问题描述】:

在这段代码中:

insert1(data: iFlower) {
    ...
    return data;
}

insert2(data: iFlower[]) {
    ...
    return data;
}

public insert (data: iFlower | iFlower[]) {
    if (data as iFlower) {
        return this.insert1(data as iFlower);
    }
    else if (data as iFlower[]) {
        return this.insert2(data as iFlower[]);
    }

当我调用insert() 函数时,根据变量data 的类型,我想调用一种方法或另一种方法。但是在这种情况下,如果data 是一个对象数组(iFlower[] 类型),它仍然进入insert1 函数...或者更好的说法,即使dataiFlower 或@987654329 @type,它会调用相同的方法。

我该如何解决这个问题? :(

【问题讨论】:

    标签: javascript typescript interface


    【解决方案1】:

    as 是一个打字稿运算符,可用于类型转换。它不会在运行时进行任何检查,因此它是无用的。您的代码基本上在运行时执行此操作:

     if(data /*as iFlower*/) // data is truthy, enters branch
    

    您可以使用Array.isArray 来确定传递的值是否为数组:

     if (Array.isArray(data)) // iFlower[]
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 2016-09-18
      • 2017-07-13
      • 2018-09-08
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      相关资源
      最近更新 更多