From d1c4b82e0b69678d6883f9be3eec950c9a1c7433 Mon Sep 17 00:00:00 2001 From: Homa Wong Date: Fri, 4 Jan 2019 16:27:09 -0800 Subject: [PATCH] feat: add RequiredPick and RequiredExcept (#9) --- README.md | 8 ++++++++ src/Required.spec.ts | 8 +++----- src/Required.ts | 10 ++++++---- src/index.ts | 2 ++ 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 055dd6d483..03b4b5f40d 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,14 @@ Make type T optional recursively. Make type T required recursively. +### `RequiredPick` + +Makes the properties specified in `U` becomes required. + +### `RequiredExcept` + +Makes the properties not specified in `U` becomes required. + ### `ValueOf` Type of the value of the properties of T. diff --git a/src/Required.spec.ts b/src/Required.spec.ts index a4ade2c187..a1e36d06a1 100644 --- a/src/Required.spec.ts +++ b/src/Required.spec.ts @@ -1,5 +1,5 @@ import { RequiredExcept, RequiredPick } from './Required'; -import { excludeUndefined } from './test-util'; +import { excludeUndefined, acceptNoUndefined } from './test-util'; test('make picked properties optional', () => { type Foo = { @@ -10,8 +10,7 @@ test('make picked properties optional', () => { let y: RequiredPick = {} as any - // https://github.com/Microsoft/TypeScript/issues/29269 - // acceptNoUndefined(y.a) + acceptNoUndefined(y.a) y.b = undefined y.c = excludeUndefined(y.c) }) @@ -26,7 +25,6 @@ test('make not picked properties optional', () => { let y: RequiredExcept = {} as any y.a = undefined - // https://github.com/Microsoft/TypeScript/issues/29269 - // acceptNoUndefined(y.b) + acceptNoUndefined(y.b) y.c = excludeUndefined(y.c) }) diff --git a/src/Required.ts b/src/Required.ts index 187d29d2a3..e07105fcef 100644 --- a/src/Required.ts +++ b/src/Required.ts @@ -1,7 +1,9 @@ +// Thanks [jack-williams](https://github.com/jack-williams) for the [solution](https://github.com/Microsoft/TypeScript/issues/29269#issuecomment-451602962) + export type RequiredPick = { - [P in keyof T]: T[P] extends undefined ? never : T[P] -} + [P in U]-?: Exclude +} & Pick> export type RequiredExcept = { - [P in keyof T]: P extends U ? T[P] : Exclude -} + [P in Exclude]-?: Exclude +} & Pick diff --git a/src/index.ts b/src/index.ts index feadcfa608..b2df7d10c8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,3 +7,5 @@ export * from './RecursiveIntersect'; export * from './RecursivePartial'; export * from './RecursiveRequired'; export * from './reduceKey'; +export * from './Required'; +export * from './ValueOf'