Seiten

Typescript duck typing

One of the main surprising feature of TypeScript in my opinion is ths so called "duck typing" that works great for interfaces in Typescript. "duck typing" is a concept for dynamic typing that has been integrated in Ruby and means:
"When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck." (by James Whitcomb Rileys)
 How does it work for interface? An Example:

Lets have the following object declarations:

let myObj = {

     lastname: "Petersen",
     surname: "Peter"
}

let myObj2 = {

     fullname: "Petersen",
     titel: "Dr."

and a simple interface declaration:

interface Name {

     lastname: string,
     surname: string
}

then the following expression is vaild in TypeScript:

let name: Name = myObj; 

but NOT this expression:

let name2: Name = myObj2;

Ok, this may be not be surprising at a second glance, but for a developer that has been shaped and stigmatized by Java for many years it is a surprisingly simple but effective feature.

Keine Kommentare:

Kommentar posten