我想为这样的对象创建一个Typescript接口。
{
"id": 34728,
"url": "https://example.com/image.jpg",
"commonNames": {
"de": ["Apfel", "Kulturapfel"],
"en": ["apple"],
"th": ["แอปเปิล"]
},
}
我的方法正确吗?我对commonNames特别不确定。
interface Food {
id: number;
url: string;
commonNames: {
[index: string]: string[];
};
}
正如已经在 @Nicholas Tower的评论你的做法是正确的。
但是,我想提出一个小小的改进建议:你有三个方面的改进。string
的类型定义中。然而,这三个 string
的意思其实是完全不同的事情。所以,我会做什么,是给他们一个。type
别名。
type Uri = string;
type Language = string;
type Name = string;
interface Food {
id: number;
url: Uri;
commonNames: {
[index: Language]: Name[];
};
}
这些只是别名,所以它们实际上并没有改变打字的任何内容。但是,它们能让人更清楚地知道这些属性是怎么回事。
另外,一个 type
别名为您提供了一个可以附加一个 TSDoc 评论到。
/**
/ * A globally unique, monotonically increasing identifier for a dictionary entry
**/
type Id = number;
/**
/ * A URI
**/
type Uri = string;
/**
/ * A URI referencing a picture of the food
**/
type PictureUri = Uri;
/**
/ * An ISO 639-1:2002 Alpha-2 Language Code
**/
type Language. = string;
/**
/ * The name of the food
**/
type Name = string;
interface Food {
id: Id;
url: PictureUri;
commonNames: {
[index: Language]: Name[];
};
}
这当然是一个极端的例子,但它表明了以下方面的价值: type
文件的别名。