是否可以从 typescript javascript 中的函数返回枚举类型。 例子:
enum Fruit{
APPLES,
ORANGES,
}
const findFruit= (arr: string[]) => {
return arr.reduce((acc, cur) => {
const result = Object.keys(Fruit).find((item) =>
cur.includes(item)
)
acc = !result? acc : result
return acc
}, '')
}
我希望能够将返回值与枚举相匹配,但现在它作为函数的字符串返回。
const type = findFruit(['I like APPLES', 'I love ORANGES'])
if(type === Fruit.APPLES) {
.....
}
上面会给我打字稿的错误
Fruit' is not comparable to type 'string'
A numeric
enum
是一个包含键值对的对象,其中键是字符串,值是数字。它还具有 reverse mappings,其中键是数字(好吧,数字字符串;对象不能真正具有 number
键)并且值是字符串。
如果你试图找到一个字符串是否包含一个字符串键然后返回相应的值,你将需要更改你的代码以便过滤掉反向映射(这样
'I enjoy 1'
不会导致一个匹配)并且它实际上在枚举中查找键。或许是这样的:
const findFruit = (arr: string[]) => {
return arr.reduce<Fruit | undefined>((acc, cur) => {
const result = (Object.keys(Fruit)
.filter(x => x !== +x + "") as Array<keyof typeof Fruit>
).find((item) => cur.includes(item));
acc = !result ? acc : Fruit[result]
return acc
}, undefined)
}
reduce()
蓄能器是 Fruit | undefined
类型而不是一些 string
。我们还 断言 在为数字字符串过滤 Object.keys()
的 Fruit
之后,我们剩下一个 keyof typeof Fruit
的数组。编译器无法推断出这一点,因为 TypeScript: Object.keys return string[].
无论如何,现在代码可以运行并返回一个
Fruit | undefined
:
const type = findFruit(['I like APPLES', 'I love ORANGES']);
// const type: Fruit | undefined
console.log(type) // 1
type
的值是1
,因为这是Fruit.ORANGES
的值