gpt4 book ai didi

javascript - 如何在 typescript 中动态访问javascript对象的键

转载 作者:行者123 更新时间:2023-11-28 16:56:11 26 4
gpt4 key购买 nike

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}`;
});

Playground Link

关于javascript - 如何在 typescript 中动态访问javascript对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com