5

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?

1 Answer 1

5

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @basarat. What I didn't understand was that any is compatible with all types (as you pointed out) in two ways. I mentally associated it with C# object, which could be downcasted from string, but not the other way around.
Actually, anything not explicitly typed has a type inferred if possible. E.g. var x = 3 becomes a number, and function a() { alert('abc') } returns void. For some reason you are allowed to return the void value that a() returns from another function, i.e. function b() { return a() } but b() is implied to return void

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.