假设我有这个:

const color = {
    red: null,
    green: null,
    blue: null
};

const newColor = ['red', 'green', 'blue'].filter(e => color[e]);

底部附近的误差为color[e],其中:

元素隐式具有"any"类型,因为表达式的类型为

我试着在TypeScript文档上到处找,但我怎么能把这个值设为interface,这样它就可以接受color[e]呢?

推荐答案

你遇到的问题不是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

Typescript相关问答推荐

如何一般设置映射类型的值

与Prettify助手类型中的对象相交?

条件类型中的Typescript二元组推理

Typescript自定义键映射

在Switch陈述中输入保护类

如何使打包和拆包功能通用?

为什么typescript不能推断类的方法返回类型为泛型''

rxjs forkJoin在错误后不会停止后续请求

如何设置绝对路径和相对路径的类型?

具有动态键的泛型类型

带占位符的模板文字类型何时扩展另一个?

类型脚本中没有接口的中间静态类

类型脚本满足将布尔类型转换为文字.这正常吗?

Angular文件上传到Spring Boot失败,多部分边界拒绝

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

自定义 Select 组件的类型问题:使用带逗号的泛型类型<;T与不带逗号的<;T&>;时出错

如何将spread operator与typescripts实用程序类型`参数`一起使用

如何在TypeScrip中使用数组作为字符串的封闭列表?

有没有更干净的方法来更新**key of T**的值?

如何实现允许扩展泛型函数参数的类型