1

As we know, the any data type is the super type of all other data types in TypeScript. I am curious why I can pass a variable of any to a function which requires a parameter of number | undefined type?

  let v1: any = 'abc';
  let v2: number | undefined = 5;

  function foo(p: number | undefined): void {
    if (typeof p === "number") {
      console.log(Math.pow(p, 2));
    } else {
      p;
      console.log("p is undefined");
    }
  }
  foo(v1); // output: p is undefined. (1)

There is no error in the above code. But I think that v1 shouldn't be a legal argument to the foo function.

  • I personally find 'any' to be a hack for lack of engineering. But I'm assuming it is allowed here because it is expected that the developer will pass the proper value to the method. It should be some kind of warning that lint provides that the value may not be the correct type. I just rewrote a ton of code on a project I'm on that the prior people used 'any' everywhere. I had no idea what kind of values were being passed until I reversed engineer the crap. – edjm Sep 23 '20 at 11:23
  • 1
    Because that's what `any` means. From the handbook it's for times when you "want to opt-out of type checking". When you type something as `any` you are telling the compiler "I got this, don't worry about it". So it doesn't. – Jared Smith Sep 23 '20 at 11:24
  • 3
    @Elijah it has nothing to do with a lack of engineering, it was specifically included for incremental typing so that you could easily gradually convert existing JS to TS without having to nail all the types up front. Totally agree that fresh TS files should not use `any`, but that's not what it's for: it's there to lower the cost of adoption in existing codebases. – Jared Smith Sep 23 '20 at 11:28
  • Why would you do `let v1: any = 'abc';`? If you're looking for automatic type inference it would be just `let v1 = 'abc';` – Aleksey L. Sep 23 '20 at 11:31
  • @AlekseyL. Just give v1 a value, no special meaning. – Matthew Gong Sep 23 '20 at 11:33
  • `any` is opt-out of type checking. https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#any – Aleksey L. Sep 23 '20 at 11:33
  • 2
    @JaredSmith I was unaware of the intent for its creation so thank you for sharing that. I can only speak to what I have seen implemented and the lack of enforcing types by developers and their quick adoption to throw 'any' at everything irks me. – edjm Sep 23 '20 at 11:37
  • The **assignability** section of the **Programming Typescript** book gives the rules for whether or not you can use a type A where another type B is required: 1) A is a subtype of or exactly the same as B. 2) A is any. – Matthew Gong Sep 24 '20 at 02:49
  • Consider using `unknown` instead (see ['unknown' vs. 'any'](https://stackoverflow.com/q/51439843/8289918)). – Lauren Yim Sep 28 '20 at 07:04

0 Answers0