3 ms·
From the snippets in the release notes: ``` function dispatch(x: string | number): SomeType { if (typeof x === "string") { return doThingWithStr
by knocte 7y ago
From the snippets in the release notes:
```
function dispatch(x: string | number): SomeType {
if (typeof x === "string") {
return doThingWithString(x);
}
else if (typeof x === "number") {
return doThingWithNumber(x);
}
process.exit(1);
}
```
It's very embarrassing in my opinion that they haven't done anything yet against having these horrible kind of type checking; comparing against a string that has the type name? "string", "number"? it's completely ludicrous.
I will not take this language seriously until this is fixed. (For sure it's still better than JavaScript, but that's about it.)
- MaulingMonkey 7y agoYou 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.