特定字符串值的打字稿数组

use*_*934 7 typescript

我有一个数组

const relations = ['profiles', 'locations', 'change_history']
Run Code Online (Sandbox Code Playgroud)

如果我想创建一个像

interface IParams {
  id: number;
  relations: []string; // how to make this an array of those relations above?
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

kar*_*fau 15

您在这里基本上有两个选择:

const string enum

您可以通过以下方式定义 const 枚举:

const enum Relation {
  profiles = 'profiles', 
  locations = 'locations', 
  change_history = 'change_history'
}

Run Code Online (Sandbox Code Playgroud)

字符串文字类型

type Relation = 'profiles' | 'locations' | 'change_history';
Run Code Online (Sandbox Code Playgroud)

就像@guijob 已经指出的那样,这将是您的界面(在两种情况下):

interface IParams {
  id: number;
  relations: Relation[];
}
Run Code Online (Sandbox Code Playgroud)

当然你也可以内联这个字符串文字类型定义

relations: ('profiles' | 'locations' | 'change_history')[];
Run Code Online (Sandbox Code Playgroud)

但请注意,在运行时不会检查值!

因此,如果您从在编译时未检查的资源(如 API 或用户输入)中添加数据,则无法保证仅存在这些值。


Gui*_*uel 11

您可以使用const 断言来轻松键入“关系”

const relations = ['profiles', 'locations', 'change_history'] as const

interface IParams {
  id: number;
  relations: typeof relations;
}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以使用Array<T>

interface IParams {
  id: number;
  relations: Array<'profiles' | 'locations' | 'change_history'>
}
Run Code Online (Sandbox Code Playgroud)

或者如果您更喜欢其他语法

interface IParams {
  id: number;
  relations: ('profiles' | 'locations' | 'change_history')[]
}
Run Code Online (Sandbox Code Playgroud)


gui*_*job 1

你可以:

enum Relation {
    profiles: 'profiles', locations: 'locations', change_history: 'change_history'
}

interface IParams {
  id: number;
  relations: Relation[];
}
Run Code Online (Sandbox Code Playgroud)