TypeScript: How to infer the exact type of the assigned value

Viewed 137

When you write this in typescript:

const x = 1;

x's type is inferred to be number. Can I make TypeScript infer this as the type 1? (So it can only get assigned the value 1).

Likewise:

const x: {
  name: 'Name',
  age: 0,
}

I would like x's type to be inferred as:

{
   name: 'Name',
   age: 0,
}

I remembered I've seen some keyword that does it but I can't find it now.

2 Answers

For x, your assumption is incorrect

x's type is inferred to be number

That would only the case if you had used the let keyword. Since you have used the const keyword, the variable can never be reassigned, so what you want to happen already happens.

const x = 1 infers the type 1 not number.

For y, the way to achieve this is using const assertions

const y = {
   name: 'Name',
   age: 0,
} as const;

This creates an object that cannot be mutated; thus y.name has the type 'Name' and y.age has the type 0

Use const contexts:

const x = 1 as const;

const y = {
  name: 'Name',
  age: 0,
} as const
Related