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

7 typescript

是否有一种 Typescript 方法要求数组必须至少有一个值?例如:

type value = "1" | "2";

export interface ISomething {
  values: value[] // < should be required and have at least one.
}
Run Code Online (Sandbox Code Playgroud)

Die*_*o V 6

type value = "1" | "2";

export interface ISomething {
  values: [value, ...value[]]
}

const empty: ISomething = { values: [] }
// Type '[]' is not assignable to type '[value, ...value[]]'.
// Source has 0 element(s) but target requires 1.

const oneValue: ISomething = { values: ["1"] }
// all good :)
Run Code Online (Sandbox Code Playgroud)


Ran*_*lta 1

尝试这个

type value = "1" | "2";

export interface ISomething {
  values: {
    0: value,
    [key: number]: value,
  }
}``
Run Code Online (Sandbox Code Playgroud)