Horje
What is the use of as const assertion in TypeScript?

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.



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Check Types in Typescript? How to Check Types in Typescript?
JavaScript Program to Find the Area of a Square JavaScript Program to Find the Area of a Square
JavaScript Program to Print Double Sided Stair-Case Pattern JavaScript Program to Print Double Sided Stair-Case Pattern
TypeScript String String.fromCodePoint() Method TypeScript String String.fromCodePoint() Method
TypeScript String.fromCharCode() Method TypeScript String.fromCharCode() Method

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14