Skip to content

Instantly share code, notes, and snippets.

@YannickLeRoux
Created January 4, 2021 16:49
Show Gist options
  • Save YannickLeRoux/56de0e5086072ba8dc508289c0c20203 to your computer and use it in GitHub Desktop.
Save YannickLeRoux/56de0e5086072ba8dc508289c0c20203 to your computer and use it in GitHub Desktop.
Typescript Runtime Typeguards
// 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