TypeScript-元素隐式地具有"any"类型,因为类型"string"的表达式不能用于索引类型 [英] TypeScript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

查看:1037
本文介绍了TypeScript-元素隐式地具有"any"类型,因为类型"string"的表达式不能用于索引类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这个:

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

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

错误位于底部附近的 color [e] 中:

The error is in color[e] near the bottom with:

元素隐式地具有"any"类型,因为类型的表达式'string'不能用于索引类型'{red:null;绿色:null;蓝色的:空值;}'.没有使用参数类型为字符串"的索引签名发现类型为'{红色:null;绿色:null;蓝色:null;}'.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ red: null; green: null; blue: null; }'. No index signature with a parameter of type 'string' was found on type '{ red: null; green: null; blue: null; }'.

我尝试在TypeScript文档中到处查找,但是我想怎么理解这个 interface ,以便它可以接受 color [e] ?

I tried looking everywhere on TypeScript docs, but how the heck am I suppose to interface this so it can accept color[e]?

推荐答案

您遇到的问题不是 color 是错误的类型,而是TypeScript推断了的类型['red','green','blue'] string [] .通常,这种类型的推断是可取的,因为(对于所有编译器都知道)您可能希望将'purple'推入推论.但是在这种情况下,您希望编译器知道唯一的成员是三个字符串文字'red''green''blue'.也就是说,您需要至少与 Array<'red'|'green'|'blue'> .

The problem you're having is not that color is the wrong type, but that TypeScript is inferring the type of ['red', 'green', 'blue'] to be string[]. Often that type of inference is desirable, since (for all the compiler knows) you might want to push 'purple' onto it. But in this case, you'd like the compiler to know that the only members are the three string literals 'red', 'green', and 'blue'. That is, you need a type at least as specific as Array<'red'|'green'|'blue'>.

假设您使用的是TS3.4或更高版本,从编译器获取这种类型推断的最简单方法是使用 const 断言:

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"];

as const 导致编译器推断只读元组).这足以解决您的错误:

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

好的,希望能有所帮助.祝你好运!

All right, hope that helps. Good luck!

链接到代码

这篇关于TypeScript-元素隐式地具有"any"类型,因为类型"string"的表达式不能用于索引类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆