-
-
Notifications
You must be signed in to change notification settings - Fork 148
/
Narrow.ts
35 lines (32 loc) · 897 Bytes
/
Narrow.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import {Try} from '../Any/Try'
import {Narrowable} from './_Internal'
/**
* @hidden
*/
type NarrowRaw<A> =
| (A extends [] ? [] : never)
| (A extends Narrowable ? A : never)
| ({[K in keyof A]: A[K] extends Function
? A[K]
: NarrowRaw<A[K]>});
/**
* Prevent type widening on generic function parameters
* @param A to narrow
* @returns `A`
* @example
* ```ts
* import {F} from 'ts-toolbelt'
*
* declare function foo<A extends any[]>(x: F.Narrow<A>): A;
* declare function bar<A extends object>(x: F.Narrow<A>): A;
*
* const test0 = foo(['e', 2, true, {f: ['g', ['h']]}])
* // `A` inferred : ['e', 2, true, {f: ['g']}]
*
* const test1 = bar({a: 1, b: 'c', d: ['e', 2, true, {f: ['g']}]})
* // `A` inferred : {a: 1, b: 'c', d: ['e', 2, true, {f: ['g']}]}
* ```
*/
type Narrow<A extends any> =
Try<A, [], NarrowRaw<A>>
export {Narrow}