Tvinge en array til å ha minst én verdi i Typescript


Finnes det en Typescript-måte å kreve at et array må ha minst én verdi? f.eks:

type value = "1" | "2";

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

Svar #1

type value = "1" | "2";

export interface ISomething {
  values: [value, ...value[]] // ← this is the non-empty array type
}

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 :)

Valgfritt kan du trekke det ut for å brukes som en generell nyttig type, som følger:

export type NonEmptyArray<T> = [T, ...Array<T>];

export interface ISomething {
  values: NonEmptyArray<value>
}

Svar #2

En annen måte uten grensesnitt:

export type NonEmptyArray<Type> = [Type, ...Array<Type>];

Bruk:

const arrayOfStrings1: NonEmptyArray<string> = ['x']; // valid
const arrayOfStrings2: NonEmptyArray<string> = ['x', 'y']; // valid
const arrayOfStrings3: NonEmptyArray<string> = ['x', 'y', 'z']; // valid
const arrayOfStrings4: NonEmptyArray<string> = [] // invalid
// Type '[]' is not assignable to type '[string, ...string[]]'.
// Source has 0 element(s) but target requires 1.ts(2322)

Relaterte artikler