Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

javascript - 如何在打字稿中动态访问javascript对象的键(How to access keys of javascript objects dynamically in typescript)

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'.
});

I want to access object keys dynamically.(我想动态访问对象键。)

But typescript is not letting me do it.(但是打字稿不是让我这样做。) Is there any way to achieve is in typescript.(有没有办法实现在打字稿中。)   ask by Shubham translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You declared array as type string[] , and key as type string .(您声明array类型string[]以及key类型string 。)

If you want Typescript to know these strings are actually keys of IObj , then tell it that:(如果您希望Typescript知道这些字符串实际上是IObj键, IObj告诉它:) const array: (keyof IObj)[] = ['fname', 'lname']; array.forEach((key: keyof IObj, index: number) => { obj[key] = `${index}`; }); Playground Link(游乐场链接)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...