1

First of all here is the code:

let vAny: any = 10
let s1: string = vAny;

console.log(typeof s1)

Here I've specified that s1 be string. But when I output the type of s1, it is a number. How's is that possible?

Kingshuk Saha
  • 84
  • 1
  • 6
  • 1
    Because using `any` says to the compiler "don't care about the type of this variable". So the compiler will obligingly let you reassign it to anything. Things like that are why you shouldn't ever use `any` unless you absolutely have to. If you have a thing and you don't know what the type is (for example the data from an API call) then use `unknown`. – Jared Smith Mar 20 '23 at 12:19
  • Does this answer your question? ["any" in Typescript](https://stackoverflow.com/questions/50875618/any-in-typescript) – Jared Smith Mar 20 '23 at 12:20

1 Answers1

1

TypeScript performs build-time checks on the type of a value. It doesn't add any kind of type casting.

Because you said vAny can be any kind of value, it doesn't check that it is a string when you assign it to s1.

If you hadn't done that…

let vAny = 10;
let s1: string = vAny;
console.log(typeof s1);

…then you would have received an error…

Type 'number' is not assignable to type 'string'.

…which would have informed you that you need to add run-time type conversation.

let vAny = 10;
let s1: string = `${vAny}`;
console.log(typeof s1);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335