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?
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?
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);