I had an impression that TypeScript allowed you to take a valid JavaScript program and "enforce" types by making a few key symbols type-safe. This would propagate the types through all the usages, and make you update all the symbol references.
This seems to be incorrect. In the following example the makeDiv
function is calling a typed make
function without checking the parameter type.
// strongly typed arguments
function make(tagName: string, className: string) {
alert ("Make: " + className.length);
}
// no typing
function makeDiv(className) {
// calling the typed function without type checking
return make("div", className);
}
makeDiv("test");
makeDiv(6); // bang!
Do I miss something here? Is there is a way to enforce "stricter" type checking? Or is this a design decision made by TypeScript creators?
This is a design decision. Anything not explicitly typed becomes implicitly typed to be of type any
. any
is compatible with all types.
var x:any = 123;
x = "bang";
To prevent implicit typing of a variable to be any
there is a compiler flag (--noImplicitAny
) starting with TypeScript 0.9.1
If you compile with this option your code will not compile unless you do:
// You need to explicitly mention when you want something to be of any type.
function makeDiv(className:any) {
// calling the typed function without type checking
return make("div", className);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With