Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structural typing is not duck typing

As mentioned in TypeScript handbook:

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”.In TypeScript, interfaces fill the role of naming these types,...


My understanding is, the above core principle does not relate to Duck typing but Structural typing, because TypeScript is static typed language.

As mentioned in wiki: It requires that type checking be deferred to runtime, and is implemented by means of dynamic typing or reflection... an object's suitability is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object.

How do I understand the above core principle of TypeScript?

like image 971
overexchange Avatar asked May 01 '18 14:05

overexchange


1 Answers

From Duck test and Duck Typing and on Wikipedia

If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

This is essentially how TypeScript interfaces work. An object just has to look like the interface rather than explicitly implement it.

Form the page you linked to:

interface LabelledValue {
    label: string;
}

function printLabel(labelledObj: LabelledValue) {
    console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

Even though myObj doesn't explicitly implement the LabelledValue interface it does have the same structure and therefore implicitly implements the interface. This is Duck Typing

UPDATE If the LabelledValue interface were defined as a class then the above code wouldn't "compile". This is Structural Typing.

Note TypeScript has no runtime checking as it is "compiled" down to JavaScript

like image 59
phuzi Avatar answered Sep 28 '22 15:09

phuzi