简体   繁体   English

Typescript 索引错误:循环输入 object 的键

[英]Typescript index error: looping through keys of typed object

I have an interface that's created as an extension of a couple of other interfaces from an external library:我有一个接口,它是作为来自外部库的几个其他接口的扩展而创建的:

interface LabeledProps extends TextProps, ComponentProps {
    id: string;
    count: number;
    ...
}

In another place in the code, I have an object of type LabeledProps and I would like to loop through all its properties:在代码的另一个地方,我有一个 LabeledProps 类型的LabeledProps ,我想遍历它的所有属性:

function myFunc(props: LabeledProps):void {
    for (let key in props) {
        const val = props[key];  // <-- ERROR IS HERE
        // do other stuff
    }
}

The line const val = props[key] throws a typescript error (though the compiled code actually runs just fine): const val = props[key]行抛出 typescript 错误(尽管编译后的代码实际上运行得很好):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LabeledProps'.

What is the right way (or ways) to accomplish this?什么是正确的方法(或方法)来完成这个? Thanks!谢谢!

( Note : I know I could add [key: string]: any to the interface definition and that will remove the error message, but I would like an actual fix, not just a hiding-the-error fix.) 注意:我知道我可以将[key: string]: any添加到接口定义中,这将删除错误消息,但我想要一个实际的修复,而不仅仅是一个隐藏错误的修复。)

In this case, you want to iterate over object pairwise.在这种情况下,您希望成对迭代对象。 There is a useful utility, called Object.entries , which removes the error.有一个有用的实用程序,称为Object.entries ,它可以消除错误。

type LabeledProps = {
    name: string,
    age: number
}

const obj: LabeledProps = {
    name: 'Maks', age: 18
}

for (let [ key, value ] of Object.entries(obj)) {
    ...
}
function myFunc(props: LabeledProps):void {
    Object.values(props).forEach(val => {
        // do other stuff
    });
}

I agree with the other answers here and the comments.我同意这里的其他答案和评论。 The responses of others were all great, and this is only offered as yet another way to do it .其他人的反应都很好,这只是提供了另一种方法

In this case you can use keyof (object operator) to explicitly tell interpreter.在这种情况下,您可以使用keyof (对象运算符)明确告诉解释器。 For example:例如:

function myFunc(props: LabeledProps):void {
    for (let key in props) {
        const val = props[key as keyof LabeledProps]; 
        // do other stuff
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM