Typ TypeScript exclude null include undefined
Sep 30 2020
Według
https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype
PrzykładNonNullable
Konstruuje typ, wykluczając null i undefined z Type.
type T0 = NonNullable<string | number | undefined>;
// ^ = type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
// ^ = type T1 = string[]
i przeczytałem, że jest to zdefiniowane jako:
type NonNullable<T> = T extends null ? never : T
Teraz chcę wykluczyć, nullale uwzględnić undefinedto jest wymagane w moim kodzie.
Jak byś to zrobił? Dzięki.
Odpowiedzi
1 Praveenkumar Oct 01 2020 at 04:02
W rzeczywistości istniejący NonNullablejest zdefiniowany jako type NonNullable<T> = T extends null | undefined ? never : T;. Ale możesz stworzyć swój własny typ narzędzia, jak poniżej i używać go.
type NonNullButUndefined<T> = T extends null ? never : T;
// Usage
type T = NonNullButUndefined<string | null | undefined>;
Stosowanie: