5 ms·
I have not used TypeScript, so can anyone explain to me what is the difference between the above the normal JavaScript code like this: function myFunction(
by paradite 10y ago
I have not used TypeScript, so can anyone explain to me what is the difference between the above the normal JavaScript code like this:
function myFunction(x) {
if (x === null) {
return;
}
console.log(x + 1); // x is now a number
}
Edit: Or is this example being used to show that TypeScript now support multiple types including null in the parameter?
I assumed that such feature would be available by default.
- ycitm 10y agoYou could call your js function with a string, and rather than a compile time error you'd get broken behaviour at runtime.
- Too 10y agoInside the function you also have to continue using x as a number, like you wouldnt be able to accidentally pass it into a function accepting only string as argument etc.
- deleted 10y ago[deleted]
- topspin 10y agoI haven't used Typescript either, but some of the differences are self evident to me. myFunction(x) can be called with any argument type; tooling can't detect an inappropriate type and output a warning/error(?), so you get to find certain mistakes the hard way; at runtime. "foo"+1 might make sense, but "foo"/1 is garbage, silently propagating 'undefined' up the stack in conventional Javascript, costing time and money for everyone. The user of myFunction(n: number | null) is provided with a meaningful signature during development, this saves time by providing precise information in a concise manner. Those of us that have spent time with statically typed languages and good tooling know what a blessing this is. The Typescript variant offers the possibility of a performance optimization; x+1 might compile down to a single instruction, as opposed to whatever runtime type check has to be invoked when the type of x isn't/can't be known at compile time. I don't know if that optimization is 'real' in practice given our contemporary javascript/typescript stack, but you can bet it will be eventually.
- adam12 10y agoyour js version: y = myFunction(1); // y = 2 y = myFunction("1"); // y = "11" the ts version wouldn't allow you to compile myFunction("1")
- mckoss 10y agoExcept for a few cases where Typescript let's you transpile ES6 syntax to JavaScript ES5, the compiler does not change your code; it just checks it for type errors. The point of the example is that Typescript recently added support for non-null types, but is flexible enough to analyze where types have been further restricted by an early function return.