Skip to main content
20

TypeScript: interface vs type, generics, and unknown vs any

EasyTypeScriptTypes

In TypeScript, what's the difference between interface and type, what are generics for, and why prefer unknown over any?

TL;DR

interface and type both describe object shapes and are mostly interchangeable. interface can be extended and merged (declaration merging); type can also express unions, intersections, tuples and mapped types. Generics let a function or type work with many types while keeping the link between input and output, like first<T>(arr: T[]): T | undefined. any turns type checking off; unknown means "could be anything", so you must narrow it before use. That makes unknown the safe choice for external data.

Key points

  • Common team rule: interface for public object shapes, type for everything else. Consistency matters more than the choice.
  • Generic constraints limit what T can be: <T extends { id: string }>.
  • Narrowing: typeof, instanceof, in, discriminated unions (a kind field), and custom type guards (x is User).
  • Utility types: Partial, Required, Pick, Omit, Record, ReturnType, Awaited.
  • Types are erased at runtime. Validate external data (API responses, forms) with a schema library such as Zod.
  • as is an assertion, not a conversion; prefer satisfies to check a value without widening it.

Example

ts
type Result<T> = { ok: true; data: T } | { ok: false; error: string }

function parse(json: string): unknown {
  return JSON.parse(json)
}

const value = parse('{"id":"1"}')
if (typeof value === 'object' && value !== null && 'id' in value) {
  console.log(value.id) // narrowed
}

function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find((item) => item.id === id)
}

Common follow-ups

  • What's a discriminated union? A union whose members share a literal field (status: 'loading' | 'success'), so a switch on it narrows the type, and never catches missing cases.
  • never vs void? void means the function returns nothing useful; never means it never returns (it throws or loops forever).

What interviewers look for

Tip

Practical judgment: when each tool fits, why unknown beats any, and that runtime validation is still needed.

  • Red flag: sprinkling any and as to silence errors.

Was this helpful?

Related questions