TypeScript uses sophisticated algorithms for type inference, inferring type annotations when explicit annotations are omitted based on assignment values, control flow context, and return statements.
window.addEventListener or .map()).let x = "hello"), TypeScript widens the type from literal "hello" to string.as const): Placing as const prevents type widening, preserving exact literal types and deep readonly properties.// Contextual Typing in Callbacks
const numbers = [10, 20, 30];
// Compiler automatically infers 'num' as number inside .map()
const doubled = numbers.map((num) => num * 2);
// Type Widening
let mutableStatus = "PENDING"; // Type widened to string
// Const Narrowing (as const)
const immutableConfig = {
endpoint: "https://api.kodersolution.com",
timeout: 5000,
roles: ["ADMIN", "USER"]
} as const;
// immutableConfig.endpoint = "other"; // Error: Cannot assign to read-only property
// immutableConfig.roles.push("GUEST"); // Error: Property 'push' does not exist on readonly array
as const for Config Objects & Enum-like Constants: Preserves exact string literal unions and prevents accidental mutations.numbers.map((num: number) => ...).Declare an object const config = { mode: "dark" } as const. What type does TypeScript infer for config.mode? (Answer: "dark", not string)
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With