From 6f413956c309839ccb0d5cbe6e84e7fc76fce0be Mon Sep 17 00:00:00 2001 From: "C. Lewis" <1657236+ctjlewis@users.noreply.github.com> Date: Fri, 21 Oct 2022 01:05:04 -0500 Subject: [PATCH] feat: `Nullable` lib type (Taylor's Version) There is already a `NonNullable`lib type, which does not seem specified in ECMA-262 and so should not be a valid basis for rejecting this PR, which I am sure many people will be thankful for as [a good chunk](https://www.google.com/search?q=%22Nullable%3CT%3E%22+includes%3Atypescript) of TS workspaces define this manually, usually as the `T | null` union. This suggestion was resisted in #19944, presumably because it's hard to know whether to use `T | null` or the example provided under the [**old handbook**](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types), `{ [P in keyof T]: T[P] | null }` (all properties on `T` assignable to `null`). There is nothing that stops us from doing both, and constructing a utility type `Nullable` which can be assigned either to `null` *or* `T` with all properties assignable to `null`: ```ts type Nullable = null | { [P in keyof T]: null | T[P] }; ``` This is not an existing utility type and so it is not as if it's breaking. This would afford a lot of convenience without any apparent drawbacks as far as I can tell, and the other PR seems to have been closed mostly on the basis of vibes only, not for any real reason. Ultimately it does seem kind of ridiculous to leave a `NonNullable` type without defining a `Nullable` one, and I suggest we take a stab at it. --- src/lib/es5.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index f224b095ba40b..0a5f9d9baa257 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1586,6 +1586,11 @@ type Extract = T extends U ? T : never; */ type Omit = Pick>; +/** + * Construct a union type from T and null. + */ +type Nullable = null | { [P in keyof T]: null | T[P] }; + /** * Exclude null and undefined from T */