Typescript not enforcing type with in function parameter

Viewed 519

I have this very simple function that accept 3 integers, add them together and print the sum out to a console.

function add(n1, n2, n3) {
    var sum : number = n1 + n2 + n3;

    console.log(sum);
}

My assumption was sum is an integer therefore it enforce the type matching. So i tried this.

add(1,2,"Henok");

TypeScript does not complain, it simply print out 3Henok. Why?


Answered in the comment blow by toskv he mentioned two thing

actually what you are writing there is var sum:number = (1 as any) + (2 as any) + ('hehe3' as any) because the types of the parameters are not specified and they default to any

and to enforce compile time complaining he add this suggestion

you can enable the noImplicitAny option when compiling and tsc will complain that you have not properly typed your code.

That works for me. thank you toskv.

1 Answers

Parameter also should specify type in typescript in order to see compilation error.

function add(n1:number, n2:number, n3:number) {
    var sum : number = n1 + n2 + n3;

    console.log(sum);
}

add(1,2, "Henok"); // compilation error

Thanks to tosky

By default parameters/variables that are not marked with any type are considered as "any" , any is literally anything (any type) and no type check is performed on any.

Don't confuse any with object, if you are using something like C# then any is similar to dynamic where type is determined at runtime.

So, expression

var sum:number = n1 + n2 + n3

is actually

var sum:number = (n1 as any) + (n2 as any) + (n3 as any)
Related