Created
January 4, 2021 16:49
-
-
Save YannickLeRoux/56de0e5086072ba8dc508289c0c20203 to your computer and use it in GitHub Desktop.
Typescript Runtime Typeguards
This file contains hidden or 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
// Asserts data is an array of values that pass a certain check | |
// Once the assertion passes (not throwing), TS will infer the proper type | |
function assertIsTypedArray<T>(arg: any, check: (value: any) => value is T): asserts arg is T[] { | |
if (!Array.isArray(arg)) throw new Error(`This is not an array: ${JSON.stringify(arg)}`); | |
if (arg.some((el) => !check(el))) | |
throw new Error(`Some elements of the array are not the expected type: ${JSON.stringify(arg)}`); | |
} | |
// exemple of check function | |
// function isITeam(arg: any): arg is ITeam { | |
// return ( | |
// typeof arg.iconUrl === 'string' && | |
// typeof arg.name === 'string' && | |
// typeof arg.id === 'string' && | |
// Array.isArray(arg.channels) | |
// ) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment