你遇到的问题不是color
是错误的类型,而是TypeScript推断['red', 'green', 'blue']
的类型是string[]
.通常,这种类型的推理是可取的,因为(据编译器所知)您可能希望将'purple'
推到它上面.但在本例中,您希望编译器知道,唯一的成员是三个字符串文本'red'
、'green'
和'blue'
.也就是说,您需要一个至少与Array<'red'|'green'|'blue'>
一样具体的类型.
Assuming you're using TS3.4 or later, the easiest way to get this kind of type inference from the compiler is to use a const
assertion:
const constAssertionTest = ["red", "green", "blue"] as const;
// const constAssertionTest: readonly ["red", "green", "blue"];
The as const
causes the compiler to infer a tuple composed of exactly the three string literals in the array, in the exact order you've set. (It's even a read-only tuple). That is good enough to fix your error:
const newColor = (['red', 'green', 'blue'] as const).filter(e => color[e]); // okay
好吧,希望有帮助.祝你好运
Link to code