Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
Eran Medan Avatar asked Oct 04 '12 05:10

Eran Medan


People also ask

Is TypeScript structural typing?

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.

What is the type of an interface TypeScript?

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.

Is TypeScript interface struct?

Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow.

What is the difference between type and interface in TypeScript?

// 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.


1 Answers

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.

like image 198
Ryan Cavanaugh Avatar answered Oct 18 '22 03:10

Ryan Cavanaugh