Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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”…..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top