Akshaya Shanbhogue
Akshaya Shanbhogue

Reputation: 1448

Why is strong type lost with `any` in typescript?

Can someone explain why the following typescript can't catch the typing problem?

function z(a: number) {
    console.log(a*a);
}

z(1); // works
z("xyz"); // fails type checking

function y(a: any){
    z(a); // I expect this statement to be erroneous
}

y(1); // works
y("xyz"); // does not fail type checking; feels like duck-typing?

In the example above, the compiler knows that y is being passed a string and therefore z is being passed a string. This should be sufficient for a transpiler error. Could someone explain the decisions that went into the transpiler design?

Thank you! :)

Upvotes: 3

Views: 533

Answers (2)

Erik Philips
Erik Philips

Reputation: 54628

Can someone explain why the following typescript can't catch the typing problem?

y("xyz"); // does not fail type checking; feels like duck-typing?

Ok so what is the signature of the method y?

function y(a: any)

Is "xyz" a valid any? Yes it is. That being said, a is now of type any, not of type string. You've explicitly told the compiler that it's any not string so since any could be a number the call is valid.

In this regard, the typescript team simply decided to not do any type checking on any because Javascript allows this type of behavior and the typescript team wanted to extend/enhance javascript not prevent you from doing something if you wanted to. any is an op-in feature and you can turn off implicitAny using the typescript compiler arguments (or tsconfig.json).

Upvotes: 1

Coding Edgar
Coding Edgar

Reputation: 1455

In y, a has any form, so it's a valid number, any is as a very permissive object, but in the case you might want to say, i don't know what a is, therefore i might want to perform some checks before calling z then you should use unknown as the least permissive type.

function y(a: unknown){
  z(a); // Argument of type 'unknown' is not assignable to parameter of type 'number'.ts(2345)
  if (typeof a === 'number') {
    z(a) // all good
  }
}

any is there for compatibility with existing javascript code or to escape safety, as of typescript 3.0 unknown is the go to type when not sure what type we're dealing with, forcing to narrow the type first. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type

Upvotes: 7

Related Questions