强制数组在Typescript中至少具有一个值

时间:2019-05-09 23:34:41

标签: typescript

是否有一种Typescript方式要求数组至少需要一个值?例如:

type value = "1" | "2";

export interface ISomething {
  values: value[] // < should be required and have at least one.
}

2 个答案:

答案 0 :(得分:1)

尝试一下

type value = "1" | "2";

export interface ISomething {
  values: {
    0: value,
    [key: number]: value,
  }
}``

答案 1 :(得分:0)

您还可以实现扩展Array的接口:

type value = "1" | "2";

interface IValueArray extends Array<value> {
  0: value; // ensure that at least one 'value' is present
}

export interface ISomething {
  values: IValueArray
}

const something1: ISomething = {
  values: ['1']
}

const something2: ISomething = {
  values: [] // type error
}