Búsqueda de sitios web

Forzar que un arreglo tenga al menos un valor en Typescript


¿Existe una manera en Typescript de requerir que un arreglo tenga al menos un valor? por ejemplo:

type value = "1" | "2";

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

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

Opcionalmente, podrías extraerlo para ser usado como un tipo de utilidad genérico, de la siguiente manera:

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

export interface ISomething {
  values: NonEmptyArray<value>
}

Respuesta #2

Otra manera sin interfaces:

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

Uso :

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)

Artículos relacionados