且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打字稿:类型中缺少索引签名

更新时间:2022-01-01 21:51:17

问题是,当推断类型时, o 是:

The problem is that when the type is inferred, then the type of o is:

{ dic: { a: number, b: number } }

{dic不同:{[name:string ]:数字}} 。至关重要的是,使用最高签名的人不允许您执行 o.dic ['x'] = 1 之类的操作。有了第二个签名,就可以了。

That's not the same as { dic: { [name: string]: number } }. Critically, with the top signature you're not allowed to do something like o.dic['x'] = 1. With the 2nd signature you are.

它们在运行时是等效类型(实际上,它们是完全相同的值),但是TypeScript的安全性很大一部分来自于这些事实并不相同,并且只有在知道对象明确地被视为一个对象的情况下,才允许您将其视为字典。这就是阻止您意外读取和写入对象上完全不存在的属性的原因。

They are equivalent types at runtime (indeed, they're the exact same value), but a big part of TypeScript's safety comes from the fact that these aren't the same, and that it'll only let you treat an object as a dictionary if it knows it's explicitly intended as one. This is what stops you accidentally reading and writing totally non-existent properties on objects.

解决方案是确保TypeScript知道它打算用作字典。这意味着:

The solution is to ensure TypeScript knows that it's intended as a dictionary. That means:


  • 在某处显式提供一种类型,以表明它是字典:

  • Explicitly providing a type somewhere that tells it it's a dictionary:

let o:MyInterface

将其设置为字典内联:

Asserting it to be a dictionary inline:

let o = {dic:< {[名称:字符串]:数字}> {'a':1,'b':2}}

确保它是TypeScript为您推断的初始类型:

Ensuring it's the initial type that TypeScript infers for you:

foo({dic:{'a':1,'b':2}})

如果在某些情况下TypeScript认为它是仅具有两个属性的普通对象,然后尝试将其用作一本字典,会很不开心。

If there's a case where TypeScript thinks it's a normal object with just two properties, and then you try to use it later as a dictionary, it'll be unhappy.