4 ms·
You can define your own type guards: function isString(x: any): x is string { return typeof x === "string"; } function isNumber(x: any
by MaulingMonkey 7y ago
You can define your own type guards:
function isString(x: any): x is string {
return typeof x === "string";
}
function isNumber(x: any): x is number {
return typeof x === "number";
}
function dispatch(x: string | number): SomeType {
if (isString(x)) {
doThingWithString(x);
} else if (isNumber(x)) {
doThingWithNumber(x);
}
process.exit(1);
}
TypeScript seeks to manage JavaScript's horrors, but importantly, it does not seek to hide them behind leaky abstractions. This is not an embarassment, but TypeScript's strength and weakness.
There is a long list of other languages that compile down to JavaScript or WASM, if you want a language built from clean foundations. But if you want to add gradual typing as a means of slowly reigning in your existing JavaScript behemoth? There is only one TypeScript.