TypeScript exclure null inclut undefined

Sep 30 2020

Selon

https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype

Non annulable

Construit un type en excluant NULL et undefined de Type.

Exemple
type T0 = NonNullable<string | number | undefined>;
//    ^ = type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
//    ^ = type T1 = string[]

et j'ai lu qu'il est défini comme:

type NonNullable<T> = T extends null ? never : T

Maintenant, je veux exclure nullmais inclure ce undefinedqui est requis dans mon code.

Comment feriez-vous cela? Merci.

Réponses

1 Praveenkumar Oct 01 2020 at 04:02

En fait, l'existant NonNullableest défini comme type NonNullable<T> = T extends null | undefined ? never : T;. Mais vous pouvez créer votre propre type d'utilitaire comme ci-dessous et l'utiliser.

type NonNullButUndefined<T> = T extends null ? never : T;

// Usage
type T = NonNullButUndefined<string | null | undefined>;

Usage: