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

时间:2019-07-30 03:55:06

标签: typescript

我有一个数组

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

如果我想创建类似

的界面
interface IParams {
  id: number;
  relations: []string; // how to make this an array of those relations above?
}

我该怎么做?

3 个答案:

答案 0 :(得分:3)

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

const string enum

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

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

字符串文字类型

type Relation = 'profiles' | 'locations' | 'change_history';

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

interface IParams {
  id: number;
  relations: Relation[];
}

当然,您也可以内联此字符串文字类型定义

relations: ('profiles' | 'locations' | 'change_history')[];

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

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

答案 1 :(得分:0)

您可以:

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

interface IParams {
  id: number;
  relations: Relation[];
}

答案 2 :(得分:0)

您可以使用 as const assertions 轻松输入“关系”

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

interface IParams {
  id: number;
  relations: typeof relations;
}

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

interface IParams {
  id: number;
  relations: Array<'profiles' | 'locations' | 'change_history'>
}

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

interface IParams {
  id: number;
  relations: ('profiles' | 'locations' | 'change_history')[]
}