Skip to content

Commit

Permalink
feat: add RequiredPick and RequiredExcept (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
unional authored Jan 5, 2019
1 parent 3902429 commit d1c4b82
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 9 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ Make type T optional recursively.

Make type T required recursively.

### `RequiredPick<T, U>`

Makes the properties specified in `U` becomes required.

### `RequiredExcept<T, U>`

Makes the properties not specified in `U` becomes required.

### `ValueOf<T>`

Type of the value of the properties of T.
Expand Down
8 changes: 3 additions & 5 deletions src/Required.spec.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -10,8 +10,7 @@ test('make picked properties optional', () => {

let y: RequiredPick<Foo, 'a'> = {} as any

// https://github.com/Microsoft/TypeScript/issues/29269
// acceptNoUndefined(y.a)
acceptNoUndefined(y.a)
y.b = undefined
y.c = excludeUndefined(y.c)
})
Expand All @@ -26,7 +25,6 @@ test('make not picked properties optional', () => {
let y: RequiredExcept<Foo, 'a'> = {} as any

y.a = undefined
// https://github.com/Microsoft/TypeScript/issues/29269
// acceptNoUndefined(y.b)
acceptNoUndefined(y.b)
y.c = excludeUndefined(y.c)
})
10 changes: 6 additions & 4 deletions src/Required.ts
Original file line number Diff line number Diff line change
@@ -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<T, U extends keyof T> = {
[P in keyof T]: T[P] extends undefined ? never : T[P]
}
[P in U]-?: Exclude<T[P], undefined>
} & Pick<T, Exclude<keyof T, U>>

export type RequiredExcept<T, U extends keyof T> = {
[P in keyof T]: P extends U ? T[P] : Exclude<T[P], undefined>
}
[P in Exclude<keyof T, U>]-?: Exclude<T[P], undefined>
} & Pick<T, U>
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ export * from './RecursiveIntersect';
export * from './RecursivePartial';
export * from './RecursiveRequired';
export * from './reduceKey';
export * from './Required';
export * from './ValueOf'

0 comments on commit d1c4b82

Please sign in to comment.