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?
TypeScript is a Structural Type System. A structural type system means that when comparing types, TypeScript only takes into account the members on the type. This is in contrast to nominal type systems, where you could create two types but could not assign them to each other.
TypeScript Interface Type TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.
Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow.
// One major difference between type aliases vs interfaces are that interfaces are open and type aliases are closed. This means you can extend an interface by declaring it a second time. // In the other case a type cannot be changed outside of its declaration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With