Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript does not enforce type check for function arguments

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?

like image 356
Vitaly Brusentsev Avatar asked Aug 19 '13 03:08

Vitaly Brusentsev


1 Answers

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);
}
like image 53
basarat Avatar answered Sep 22 '22 13:09

basarat