-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(validator): add
isWhat
util function, thanks to microsoft/Type…
- Loading branch information
Showing
1 changed file
with
21 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
export const notMatched: unique symbol = Symbol('notMatched') | ||
|
||
/** | ||
* By using the built-in type guarding strategy, you can indirectly generate an `is` function without explicitly declaring | ||
* the return type of the `is` function. This allows you to focus less on type declarations. | ||
* | ||
* @example | ||
* ```ts | ||
* const onlyStrings = ['a', 'b', 1, 2] | ||
* .filter((x): x is string => typeof x === 'string') | ||
* // Code like the one above can be handled using `isWhat` without explicitly declaring the return type | ||
* const onlyStrings = ['a', 'b', 1, 2] | ||
* .filter(isWhat(x => typeof x === 'number' ? x : notMatched)) | ||
* // The general pattern can be written as | ||
* const onlyWhatType = ['a', 'b', 1, 2] | ||
* .filter(isWhat(x => (${write type guard conditional expression}) ? x : notMatched)) | ||
* ``` | ||
*/ | ||
export function isWhat<T>(match: (x: unknown) => T | typeof notMatched): (x: unknown) => x is T { | ||
return (x): x is T => match(x) !== notMatched | ||
} |