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:
interfacefor public object shapes,typefor everything else. Consistency matters more than the choice. - Generic constraints limit what
Tcan be:<T extends { id: string }>. - Narrowing:
typeof,instanceof,in, discriminated unions (akindfield), 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.
asis an assertion, not a conversion; prefersatisfiesto 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 aswitchon it narrows the type, andnevercatches missing cases. nevervsvoid?voidmeans the function returns nothing useful;nevermeans 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
anyandasto silence errors.