Open In App

What is the use of as const assertion in TypeScript?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The as const assertion is used to infer the variables with literal types in TypeScript. If the as const assertion is used with any kind of variable it narrows down its type to a literal type which means the variables defined using the as const assertion can not be modified once they are assigned a value initially. It will be useful when you want to create arrays or objects whose values you don’t want to change again throughout the code.

Example: The below code will explain the use of the as const assertion to infer the literal type for variables.

Javascript




const myObj = {
  name: "GFG",
  est: 2009
}
myObj.name = "GeeksforGeeks";
console.log(myObj);
 
const myObj2 = {
  name: "GFG",
  est: 2009
} as const;
myObj2.name = "GeeksforGeeks";
myObj2.desc = "Geeks Learning Together";
console.log(myObj2);


Output:

name: "GeeksforGeeks"
est: 2009
Error: Cannot assign to 'name' because it is a read-only property.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads