有没有一种方法可以在联合类型上调用数组原型方法?

时间:2019-11-19 10:16:00

标签: javascript arrays typescript union-types

以下面的代码为例:


    class Something {

      public getItems(): string | string[] {

        return items;
      }

    } 

是否可以在调用getItems()时访问数组原型方法?

像这样吗?

let something = new Something();

const items = something.getItems();

items.filter(i => i.length > 2); // here for example 

4 个答案:

答案 0 :(得分:2)

为什么不能的唯一问题是返回的类型getItemsstring | string[]string部分存在问题,因为字符串没有Array原型。为了使用getItems返回的值,我们需要使用类型警卫来缩小类型。

const items = something.getItems(); // items is string | string[]

if (typeof items !== 'string') {
  // now type is narrowed to string[]
  items.filter(i => i.length > 2); // fully type safe
} else {
  // here you have a string
}

我们还可以通过将string的结构范围缩小到字符串数组来完成更多的工作。

const items = something.getItems(); // items is string | string[]
// in line below I am bringing both possible values into array structure
const finalItems = typeof items === 'string' ? [items] : items; 
finalItems.filter(i => i.length > 2); // fully type safe

上面重要的是[items],我在其中将单个字符串值放入数组,这是由于finalItems只有一种类型-string[]

答案 1 :(得分:1)

concat可以接受以下类型的参数:字符串或字符串数​​组。无论哪种情况,它都给出相同的结果(数组):

let filtered = [].concat(items).filter(i => i.length > 2);

但是,我建议调整Something的接口,使其已经处理好了,即使只有一个字符串也只能返回数组。

答案 2 :(得分:0)

有可能,但您只需要考虑一件事。 getItems()方法返回数组或字符串。如果返回字符串,则您的应用程序将引发错误cannot read property of undefined。为防止这种情况,您的方法应始终返回一个数组。

答案 3 :(得分:0)

您可以这样做

let something = new Something();
const items: any = something.getItems();
items.filter(i => i.length > 2);
  • 在这种情况下,编译错误将被抑制。
  • 但是要使代码在运行时工作,返回值应为字符串[]。
  • 如果不是,则将引发 TypeError:items.filter不是函数
相关问题