【问题标题】:typescript array of specific string values特定字符串值的打字稿数组
【发布时间】:2019-12-07 09:33:36
【问题描述】:

我有一个数组

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

如果我想创建一个类似的界面

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

我该怎么做?

【问题讨论】:

  • string[] 怎么样?还是您在寻找更具体的东西?比如['profiles', 'locations', 'change_history']本身
  • 寻找特定的东西。谢谢

标签: typescript


【解决方案1】:

你可以:

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

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

【讨论】:

【解决方案2】:

这里基本上有两种选择:

const string enum

您可以通过以下方式定义一个常量枚举:

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 或用户输入)添加数据,则无法保证仅存在这些值。

【讨论】:

    【解决方案3】:

    您可以使用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')[]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-28
      • 2018-06-11
      • 2023-02-23
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多