Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
Last active November 4, 2022 11:22
Show Gist options
  • Save dmorosinotto/4af3bd8c0ae7240095bbe28508a42980 to your computer and use it in GitHub Desktop.
Save dmorosinotto/4af3bd8c0ae7240095bbe28508a42980 to your computer and use it in GitHub Desktop.
Nullable types helper (very short ^_^) for TypeScript
export type N<T> = T | null;
export type NU<T> = T extends undefined ? never : T;
export type NN<T> = NonNullable<T>;
//SAMPLE USE CASES
interface TryNull{
nullable: N<number>;
maybe?: string;
flag?: N<boolean>;
same: { is: "same", type: "NON nullable" }
}
type TSame = TryNull['same'] // { is: "same", type: "NON nullable" }
type ns = N<TSame> // null | { is: "same", type: "NON nullable" }
type is = NU<TSame> // { is: "same", type: "NON nullable" }
type ok = NN<TSame> // { is: "same", type: "NON nullable" }
type TFlag = TryNull['flag']; // boolean | null | undefined
type b = NN<TFlag>; // boolean
type bn = NU<TFlag>; // boolean | null
type ss = NU<TryNull['maybe']>; // string
type ts = NU<TryNull['maybe']>; // string
type tn = NN<TryNull['nullable']>; //number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment