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
453 views
in Technique[技术] by (71.8m points)

javascript - 如何获取数组中的属性名称字符串列表 <Object> 作为打字稿中的类型(How can I get the attribute name string list in Array<Object> as type in Typescript)

We have a constant like this

(我们有一个这样的常数)

const list = [
  {id: '01', name: 'apple', ...},
  {id: '02', name: 'banana', ...},
  ...
]

How can we get the type like this

(我们如何获得这样的类型)

type XXX = "apple" | "banana" | ...

Without writing apple and banana once more to define their type in original constant.

(无需再编写applebanana即可使用原始常量定义它们的类型。)


We want to generate the type from the constant itself.

(我们想从常量本身生成类型。)

I've noticed the pick in lib.es5.d.ts .

(我注意到lib.es5.d.tspick 。)

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

But unclear about how to implement it as a best practice.

(但尚不清楚如何将其作为最佳实践来实施。)


Is there any ideas?

(有什么想法吗?)

  ask by keikai translate from so

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

1 Reply

0 votes
by (71.8m points)
等待大神答复

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

...