gpt4 book ai didi

javascript - 有没有办法在联合类型上调用数组原型(prototype)方法?

转载 作者:行者123 更新时间:2023-11-28 16:56:46 24 4
gpt4 key购买 nike

考虑以下代码作为示例:


class Something {

public getItems(): string | string[] {

return items;
}

}

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

类似这样的事情吗?

let something = new Something();

const items = something.getItems();

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

最佳答案

唯一不能解决的问题是类型 getItems返回,它是 string | string[]string部分是一个问题,因为字符串没有数组原型(prototype)。为了使用 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[]

关于javascript - 有没有办法在联合类型上调用数组原型(prototype)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58931567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com