Skip to content
Plurafy

TypeScript Interview Questions

Top 100 Interview Questions with Answers

TypeScript, a const assertion (as const) tells the compiler to infer the narrowest, most specific type possible for an expression.

When you apply as const to a literal value, it triggers three critical behaviors at compile time:

  1. Prevents type widening: A string literal like "hello" stays "hello" instead of widening to string.
  2. Deep readonly objects: Object properties are marked readonly recursively.
  3. readonly tuples: Array literals are converted into fixed-length, immutable readonly tuples instead of mutable arrays like string[].

Type Widening vs. Const Assertion

By default, TypeScript assumes you will want to mutate variables, so it widens specific literal values to their broader base types.

// --- Without "as const" ---
const status1 = "success";
// Type is the literal "success" because it's a block-scoped `const` variable.
let status2 = "success";
// Type is widened to `string` because a `let` variable can be reassigned.
const config = {
theme: "dark", // Type is widened to `string`
retries: 3 // Type is widened to `number`
};
// --- With "as const" ---
let status3 = "success" as const;
// Type is strictly the literal "success"
const configAsConst = {
theme: "dark",
retries: 3
} as const;
/*
The inferred type of configAsConst is now:
{
readonly theme: "dark";
readonly retries: 3;
}
*/

Arrays to Readonly Tuples

Without a const assertion, arrays are inferred to contain any element matching the union of their contents, and their length remains dynamic. With as const, the position and exact values are locked in.

// Inferred type: (string | number)[]
const coordinates = [10, 20, "GMT"];
coordinates.push(40); // Allowed at compile time
// Inferred type: readonly [10, 20, "GMT"]
const exactCoordinates = [10, 20, "GMT"] as const;
// exactCoordinates.push(40);
// Error: Property 'push' does not exist on type 'readonly [10, 20, "GMT"]'.

Practical Use Case: Replacing Enums

A highly practical pattern in modern TypeScript is using as const alongside typeof to create clean, zero-cost alternatives to native TypeScript enum structures.

// 1. Create a plain JavaScript object wrapped in a const assertion
const ROLES = {
Admin: "ADMIN",
User: "USER",
Guest: "GUEST",
} as const;
// 2. Extract a union type from the object's values
type Role = typeof ROLES[keyof typeof ROLES];
// Type evaluates exactly to: "ADMIN" | "USER" | "GUEST"
// 3. Use it cleanly in functions
function assignRole(role: Role) {
console.log(`Role assigned: ${role}`);
}
assignRole(ROLES.Admin); // Works
assignRole("USER"); // Works! (Enums wouldn't allow this raw string literal)
// assignRole("SUPERADMIN"); // Error: Argument of type '"SUPERADMIN"' is not assignable