【问题标题】:Typescript index error: looping through keys of typed object打字稿索引错误:循环通过键入对象的键
【发布时间】:2021-06-28 18:07:48
【问题描述】:

我有一个接口,它是作为来自外部库的几个其他接口的扩展而创建的:

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

在代码的另一个地方,我有一个LabeledProps 类型的对象,我想遍历它的所有属性:

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

const val = props[key] 行会引发打字稿错误(尽管编译后的代码实际上运行良好):

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

实现此目的的正确方法(或方法)是什么?谢谢!

(注意:我知道我可以将[key: string]: any 添加到接口定义中,这将删除错误消息,但我想要一个实际的修复,而不仅仅是隐藏错误的修复.)

【问题讨论】:

  • 不能使用let key:any in props?
  • 不,因为“for...in 语句的左侧不能使用类型注释”
  • 使用for ... in 进行迭代的常见模式是:let key: keyof (typeof obj); for (key in obj) ...
  • @aleksxor 谢谢,成功了!

标签: javascript typescript for-loop


【解决方案1】:

在这种情况下,您希望成对地迭代对象。有一个有用的实用程序,称为 Object.entries,它可以消除错误。

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

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

for (let [ key, value ] of Object.entries(obj)) {
    ...
}

【讨论】:

    【解决方案2】:
    function myFunc(props: LabeledProps):void {
        Object.values(props).forEach(val => {
            // do other stuff
        });
    }
    

    我同意这里的其他答案和 cmets。其他人的反应都很好,这只是提供另一种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2020-04-20
      • 2021-12-17
      • 2021-12-11
      相关资源
      最近更新 更多