定义一个只能包含一个属性的 TypeScript 类型。

huangapple go评论67阅读模式
英文:

define a typescript type that can contain only one single property

问题

如何在 TypeScript 类型中表示这个 JSON:

type MetaItem = Record<string, string>;
type Meta = MetaItem[];

meta 是一个由 meta_item 对象组成的数组,其中每个 meta_item 只有一个属性

meta_item应该是一个 URI,可以是任何内容。

这样表示是否可行?

英文:

I have this JSON :

 &quot;meta&quot;          : [
   {&quot;http://example.com/rel/1/&quot; : &quot;my meta 14&quot;},
   {&quot;http://example.com/rel/2/&quot; : &quot;345&quot;}
 ],

How can I express this in a typescript type ?

meta is an array of meta_item objects,
where each meta_item has only one property.

The key of meta_item should be an URI, the value can be anything.

Is this possible ?

Thanks !

答案1

得分: 0

如果我有选择,我可能会选择使用字典:

const meta: { [id: string] : any; } = {};
meta[&quot;http://example.com/rel/1/&quot;] = &quot;my meta 14&quot;
meta[&quot;http://example.com/rel/2/&quot;] = &quot;345&quot;

或者,如果你想要数组:

type meta_item = {
  [url: string]: any;
};

meta: meta_item[];
英文:

If I had the choice, I'd probably go for a dictionary:

const meta: { [id: string] : any; } = {};
meta[&quot;http://example.com/rel/1/&quot;] = &quot;my meta 14&quot;
meta[&quot;http://example.com/rel/2/&quot;] = &quot;345&quot;

Or, if you want the array:

type meta_item = {
  [url: string]: any;
};

meta: meta_item[];

huangapple
  • 本文由 发表于 2023年3月31日 18:58:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定