Question presented to candidate:
"In TypeScript you can write interface User { ... } or type User = { ... }. What is actually different between the two, and how do you decide which one to use?"
What a strong answer should cover:
- For a plain object shape the two are interchangeable: same checking, both erased at run time, a class can
implementseither - Only
typecan name a union, a primitive, a tuple, a mapped or a conditional type;interfaceonly describes object (and function or constructor) shapes - Extending:
interface X extends Yreports a conflicting member as an error (TS2430), whileY & { ... }silently producesneverfor that member - Declaration merging: two
interfacedeclarations with the same name merge (used for module augmentation and global types); twotypealiases with the same name are a duplicate identifier error (TS2300) - The subtle one: an object
typealias is assignable toRecord<string, T>(implicit index signature), aninterfaceis not - A sensible team rule (interfaces for object shapes you may extend,
typefor unions and computed types) and the performance note: the TypeScript wiki prefersextendsover large intersections
Code / implementation expected: Optional β the same shape written both ways, plus a union that only type can express.