Витязи Team
Витязи Team

Reputation: 369

Why is the behavior of the typescript different when declaring variables?

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

Answers (1)

jason.
jason.

Reputation: 375

let

You declare a variable using let

let a = 'hello';

Typescript can infer:

  1. ✅ The variable's declaration → (type becomes any)
  2. ✅ The variable's type → (type becomes string)
  3. ❌ The variable's content → ?

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:

  1. ✅ The variable's declaration → (type becomes any)
  2. ✅ The variable's type → (type becomes string)
  3. ✅ The variable's content → (type becomes '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

Related Questions