as const
makes the attributes of an object constant, and does the same thing like Object.freeze()
, yet not a runtime. Therefore, it makes sure TypeScript understands that the provided type for the attribute stays the same.
It is often a useful fix when the pure const
declaration is not enough.
const person = {
name: "Max",
age: 22
}
function takeString(param: string) {}
// will give a warning, that person.name might be any, as attributes are not constant
takeString(person.name)
Solving this problem:
const person = {
name: "Max",
age: 22
} as const