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
implementsclauses 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
CelsiusandFahrenheitorUserIdandOrderIdare interchangeable;{}accepts almost anything - How to get nominal behaviour when you need it: branded types, or classes with
private/#privatemembers, 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.