Search code examples
c#typescriptstructural-typing

What is "Structural Typing for Interfaces" in TypeScript


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?


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.