UNPKG

1.4 kBTypeScriptView Raw
1import type {IsNull} from './is-null';
2
3/**
4Returns a boolean for whether the given type is `unknown`.
5
6@link https://github.com/dsherret/conditional-type-checks/pull/16
7
8Useful in type utilities, such as when dealing with unknown data from API calls.
9
10@example
11```
12import type {IsUnknown} from 'type-fest';
13
14// https://github.com/pajecawav/tiny-global-store/blob/master/src/index.ts
15type Action<TState, TPayload = void> =
16 IsUnknown<TPayload> extends true
17 ? (state: TState) => TState,
18 : (state: TState, payload: TPayload) => TState;
19
20class Store<TState> {
21 constructor(private state: TState) {}
22
23 execute<TPayload = void>(action: Action<TState, TPayload>, payload?: TPayload): TState {
24 this.state = action(this.state, payload);
25 return this.state;
26 }
27
28 // ... other methods
29}
30
31const store = new Store({value: 1});
32declare const someExternalData: unknown;
33
34store.execute(state => ({value: state.value + 1}));
35//=> `TPayload` is `void`
36
37store.execute((state, payload) => ({value: state.value + payload}), 5);
38//=> `TPayload` is `5`
39
40store.execute((state, payload) => ({value: state.value + payload}), someExternalData);
41//=> Errors: `action` is `(state: TState) => TState`
42```
43
44@category Utilities
45*/
46export type IsUnknown<T> = (
47 unknown extends T // `T` can be `unknown` or `any`
48 ? IsNull<T> extends false // `any` can be `null`, but `unknown` can't be
49 ? true
50 : false
51 : false
52);