Reputation: 369
Why is the behavior of the typescript different when declaring variables?
let a = "asdasd"; // here type is string
const b = "asdads"; // here type is "asdads". Why not string? if i try assign this as type for another variable it must be initializing with this value
const something = { // here type is {a:"something"}
a:"something"
}
let somethingg = { // here type is also as above. But must be object
a:"something"
}
Upvotes: 2
Views: 125
Reputation: 375
let
You declare a variable using let
let a = 'hello';
Typescript can infer:
any
)string
)This is because you may change the value of the variable elsewhere in code:
let a = 'hello';
a = 'bye';
const
You declare a variable using const
const a = 'hello';
Typescript can infer:
any
)string
)'hello'
)This is because you may not change the value of the variable elsewhere in code:
const a = 'hello';
a = 'bye'; // Uncaught TypeError: Assignment to constant variable.
Upvotes: 3