interface IObj {
fname: string;
lname: string;
}
const obj: IObj = <IObj>{};
const array: string[] = ['fname', 'lname'];
array.forEach((key: string, index: number) => {
obj[key] = `${index}`; // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IObj'.
});
我想动态访问对象键。但 typescript 不允许我这样做。 有什么方法可以在 typescript 中实现。
最佳答案
您将 array
声明为 string[]
类型,并将 key
声明为 string
类型。如果你想让 Typescript 知道这些字符串实际上是 IObj 的键,那么告诉它:
const array: (keyof IObj)[] = ['fname', 'lname'];
array.forEach((key: keyof IObj, index: number) => {
obj[key] = `${index}`;
});
关于javascript - 如何在 typescript 中动态访问javascript对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098788/