[英]How to define a list of optional strings as property of an interface in Typescript
I would like to have a property on an interface, interests
for example, which is a list of one or more pre-defined interests.我想在界面上有一个属性,例如
interests
,它是一个或多个预定义兴趣的列表。
For example, the interface would look something like:例如,界面看起来像:
// User Data Model
export default interface User {
uid: String;
email: string;
username: string;
firstName?: String;
lastName?: String;
interests: partial<Interests>;
}
// Interests data model
type Interests = ['swimming', 'running', 'movies', 'hiking'];
And the implementation could be as follows:实现可能如下:
const user: User = {
uid: "123abc",
email: "joe@soap.com",
username: "soapMctavish",
firstName: "Joe",
lastName: "Soap",
interests: ["swimming", "movies"]
}
The goal is to avoid defining interests as follows:目标是避免将利益定义如下:
export default interface User {
...
interests: "Movies" | "Swimming" | "Hiking" | ...etc;
}
And to have the ability to define 1 through n interests per user.并且能够为每个用户定义 1 到 n 个兴趣。
You want to somehow get the union你想以某种方式获得工会
'swimming' | 'running' | 'movies' | 'hiking'
from从
type Interests = ['swimming', 'running', 'movies', 'hiking'];
You can achieve that by indexing into Interests
with number
:您可以通过使用
number
索引到Interests
来实现:
Interests[number] // 'swimming' | 'running' | 'movies' | 'hiking'
Then you wrap this union into an array for the desired result:然后将此联合包装到一个数组中以获得所需的结果:
Interests[number][] // ('swimming' | 'running' | 'movies' | 'hiking')[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.