TypeScript Developer interview question · Most asked
What is structural typing in TypeScript?
Summary
TypeScript checks compatibility by shape (structure), not by declared names: a value is assignable to a type if it has all the required members with compatible types, regardless of which class or interface created it.
Longer Answer
This differs from nominal typing in Java or C#. Two unrelated interfaces with the same members are interchangeable. Excess property checks only apply to fresh object literals. When you need nominal-like behavior (e.g., not mixing UserId and OrderId strings), use branded types.
Code Example
interface Point { x: number; y: number }
class Vector { constructor(public x: number, public y: number) {} }
const p: Point = new Vector(1, 2); // OK: same shape
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
declare function getUser(id: UserId): void;
// getUser("abc" as OrderId); // Error: brands differ
Key Points
- Compatibility by shape
- Unrelated types with same shape are interchangeable
- Excess property checks on object literals
- Brands simulate nominal typing
More most-asked TypeScript Developer questions
- What is TypeScript and what problems does it solve?
- What are the differences between `interface` and `type` aliases?
- Explain `any`, `unknown` and `never`.
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is type narrowing and what techniques does TypeScript support?
- What are mapped types? Show how `Partial` or `Readonly` could be implemented.