Type InferenceIntermediate
1Question 1 of 1
typescriptHow does Type Inference work in TypeScript and when should you omit explicit annotations?
Explanation & Concept
TypeScript's compiler automatically infers types based on variable initializers, return values, and contextual usage. Writing redundant type annotations clutters code without adding safety.
Code Example
typescript
// 1. Inferred automatically as 'string' (no need for ': string')
let userGreeting = "Welcome back!";
// 2. Return type automatically inferred as 'number'
const addNumbers = (a: number, b: number) => a + b;
// 3. 'as const' infers literal types and readonly arrays
const ROLES = ["admin", "editor", "guest"] as const;
type Role = typeof ROLES[number]; // "admin" | "editor" | "guest"How It Works & Key Takeaways
Using `as const` instructs TypeScript to infer the narrowest possible literal types and mark array elements as `readonly`.
Mock Test · 1 Questions · Optional
Ready for Discriminated Unions?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions