Skip to the solution
MediumFrontend9 min read

What is structural typing?

289 views

The problem

Question presented to candidate: "TypeScript is often described as structurally typed. What does that mean, how is it different from Java or C#, and where can it surprise you?"

What a strong answer should cover:

  • Structural typing: a value is assignable to a type when it has the required members with compatible types; names and implements clauses do not matter
  • Contrast with nominal typing (Java, C#), where a class must explicitly declare that it implements an interface
  • Extra members are allowed (width subtyping), except for the excess property check on fresh object literals
  • The surprises: two same-shaped types such as Celsius and Fahrenheit or UserId and OrderId are interchangeable; {} accepts almost anything
  • How to get nominal behaviour when you need it: branded types, or classes with private/#private members, which compare by declaration
  • Why TypeScript chose it: JavaScript code is duck-typed and objects are often plain literals, so shape is what really matters

Code / implementation expected: Optional β€” a class and an object literal that both satisfy an interface they never mention.

  • structural-typing

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptCompatibility by shape, excess property checks and {}
TypeScriptWhere it bites, and three ways to get nominal behaviour

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 55 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How does `satisfies` validate shape without widening literal types?

Continue