Table of contents
Open Table of contents
Understanding Type Inference with Variables
Let’s start by examining a simple scenario with a variable named “age.” When declared using “let,” TypeScript infers it as a mutable number, allowing for reassignment.
let age = 25;
age = 30; // Works fine
However, if we declare “age” as a “const,” TypeScript not only prevents reassignment but also infers a literal type.
const age = 40;
// age = 50; // Error: 50 is not assignable to type 40
Here, TypeScript recognizes “age” as the literal type 31, providing a more stringent form of type checking.
The same principle applies to strings.
Arrays and Objects
Array and object manipulation introduces additional complexities. In the case of arrays, even when declared as a “const,” individual elements can still be modified.
const tsPeople = ["Bod", "Kevin"];
tsPeople[0] = "Jakob"; // Works fine
To enforce immutability for each array member, use “as const”
const tsPeople = ["Bod", "Kevin"] as const;
// tsPeople[0] = "Jakob"; // Error: Index signature in type 'readonly ["Bod", "Kevin"]' prohibits assignment
Similar principles apply to objects
const team = { dev: "Kevin" };
team.dev = "Jakob"; // Works fine
To lock down both the object itself and its properties, use “as const”.
const team = { dev: "Kevin" } as const;
team.dev = "Jakob"; // // Error: Cannot assign to 'dev' because it is a constant
Conclusion
Developing a comprehensive understanding of how TypeScript infers types and handles immutability is crucial for effective type checking and inference. By embracing read-only properties and employing “as const” judiciously, developers can enhance the reliability and robustness of their TypeScript code.