What is "Structural Typing for Interfaces" in TypeScript
Asked Answered
M

2

18

In his blog post about TypeScript, Mark Rendle is saying, that one of the things he likes about it is:

"Structural typing for interfaces. I really wish C# could do that"

What did he mean by that?

Makeup answered 4/10, 2012 at 5:8 Comment(1)
I've briefly read this #2831675 which clarifies it a little, but still would like to know how it's used in TypeScriptMakeup
L
19

Basically, it means that interfaces are compared on a "duck typing" basis rather than on a type identity basis.

Consider the following C# code:

interface X1 { string Name { get; } }
interface X2 { string Name { get; } }
// ... later
X1 a = null;
X2 b = a; // Compile error! X1 and X2 are not compatible

And the equivalent TypeScript code:

interface X1 { name: string; }
interface X2 { name: string; }
var a: X1 = null;
var b: X2 = a; // OK: X1 and X2 have the same members, so they are compatible

The spec doesn't cover this in much detail, but classes have "brands" which means the same code, written with classes instead of interfaces, would have an error. C# interfaces do have brands, and thus can't be implicitly converted.

The simplest way to think about it is that if you're attempting a conversion from interface X to interface Y, if X has all the members of Y, the conversion succeeds, even though X and Y might not have the same names.

Liquidator answered 4/10, 2012 at 5:29 Comment(0)
H
2

Think about.

class Employee { fire: = ..., otherMethod: = ...}
class Missile { fire: = ..., yetMoreMethod: = ...}
interface ICanFire { fire: = ...}
val e = new Employee
val m = new Missile
ICanFire bigGuy = if(util.Random.nextBoolean) e else m
bigGuy.fire

What if we said:

interface IButtonEvent { fire: = ...}
interface IMouseButtonEvent { fire: = ...}
...

TypeScript will allow this, C# will not.

As TypeScript aims to work well with the DOM that uses “loose” typing, it is the only sensible choose for typescript.

I leave it up to the reader to decide if they like “Structural typing”…..

Heliport answered 12/2, 2014 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.