3 ms·
If you prefer the "or throw" approach to handling null values, you can write a little helper to get something like it in TypeScript: function assert<T>(v:
by danvk 6y ago
If you prefer the "or throw" approach to handling null values, you can write a little helper to get something like it in TypeScript:
function assert<T>(v: T | null | undefined, message?: string): asserts v is T {
if (v === null || v === undefined) {
throw new Error(message);
}
}
function parseFile(file: File | null) {
assert(file, 'File must exist');
// TS now infers type of file as File
}
Check out the TypeScript 3.7 release notes for more on assertion functions: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions https://www.typescriptlang.org/docs/handbook/release-notes/t...