WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Expert · question 63 of 100

Can you explain the differences between ’as const’ vs ’const’ assertions in TypeScript?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

In TypeScript, ‘const‘ declarations and ‘as const‘ assertions serve different purposes but are related in the sense that they both deal with immutability.

1. ‘const‘ declarations:

‘const‘ is used to declare a constant variable whose value cannot be changed after its initialization. It creates read-only references within the scope of the declaration.

const pi = 3.14159;
pi = 3.14; // TypeScript Error: Cannot assign to 'pi' because it is a constant or a read-only property.

2. ‘as const‘ assertions:

‘as const‘ assertion, introduced in TypeScript 3.4, is a way to make the entire structure (object or array) immutable, which means that once created, it cannot be modified. It also narrows the type of the literals used. This is commonly called "const assertions" or "const contexts."

For example, consider this code:

const colors = ['red', 'green', 'blue'] as const;

colors.push('yellow'); // TypeScript Error: Property 'push' does not exist on type 'readonly ["red", "green", "blue"]'.

When using the ‘as const‘ assertion, TypeScript has inferred the ‘colors‘ variable as an immutable tuple with the exact types of the strings (‘"red"`, ‘"green"`, and ‘"blue"`), instead of the default mutable array of strings (‘string[]‘).

Here’s another example illustrating the differences between objects with and without ‘as const‘:

const obj1 = {
  a: 1,
  b: 'hello',
};
// TypeScript infers 'obj1' as:
// {
//    a: number;
//    b: string;
// }

const obj2 = {
  a: 1,
  b: 'hello',
} as const;
// TypeScript infers 'obj2' as:
// {
//    readonly a: 1;
//    readonly b: "hello";
// }

To recap, here are the key differences between ‘const‘ declarations and ‘as const‘ assertions in TypeScript:

- ‘const‘ is simply used to declare constant variables with an immutable value, while ‘as const‘ is used for making an entire structure (object or array) read-only.

- ‘const‘ declarations do not change the type of the variables, while ‘as const‘ may narrow down the types of the variables (e.g., from ‘number‘ to the specific value used in the literal).

In conclusion, ‘const‘ is used to make variables read-only, while ‘as const‘ is used to make an entire structure-of-literals immutable and narrow down the types to their exact literal values.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics