打字稿:类型中缺少索引签名 [英] Typescript: Index signature is missing in type

查看:509
本文介绍了打字稿:类型中缺少索引签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 MyInterface.dic 像字典 name:value ,我对它的定义如下:

I want MyInterface.dic to be like a dictionary name: value, I define it as follows:

interface MyInterface {
    dic: { [name: string]: number }
}

现在,我创建一个函数来等待我的类型:

Now I create a function which waits for my type:

function foo(a: MyInterface) {
    ...
}

然后输入:

let o = {
    dic: {
        'a': 3,
        'b': 5
    }
}

我期望 foo(o)是正确的,但是编译器正在下降:

I'm expecting foo(o) to be correct, but the compiler is falling:

foo(o) // Typescript error: Index signature is missing in type { 'a': number, 'b': number }

我知道可能存在强制转换: let o:MyInterface = {...} 其中可以解决问题,但问题是,为什么打字稿无法识别我的打字稿?

I know there is a possible casting: let o: MyInterface = { ... } which do the trick but the question is, why typescript is not recognizing my type?

额外:如果声明 o 内联,则可以正常工作:

Extra: works fine if o is declared inline:

foo({ 
  dic: {
    'a': 3, 
    'b': 5
  }
})


推荐答案

问题是,当推断类型时, 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.

这篇关于打字稿:类型中缺少索引签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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