我有一个接口,它是作为外部库中其他几个接口的扩展创建的:
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]
行抛出一个typescript错误(尽管编译后的代码实际上运行得很好(:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LabeledProps'.
实现这一目标的正确方法是什么?谢谢
(注意:我知道我可以将[key: string]: any
添加到接口定义中,这将删除错误消息,但我想要一个实际的修复,而不仅仅是隐藏错误修复。(
在这种情况下,您希望成对地迭代对象。有一个有用的实用程序,称为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
});
}
我同意这里的其他答案和评论。其他人的反应都很好,这只是作为提供的另一种方式。
在这种情况下,您可以使用keyof
(对象运算符(显式地告诉解释器。例如:
function myFunc(props: LabeledProps):void {
for (let key in props) {
const val = props[key as keyof LabeledProps];
// do other stuff
}
}