TypeScript and Duck Typing

Ajay Bhosale
2 min readJan 17, 2017

--

TypeScript is one of the popular languages today, and probable candidate to become the top programming language for 2017 according to TIOBE Index for January 2017. It provides optional static typing to JavaScript (and many other features). It has an interesting implementation for Duck Typing, a clear understanding of which can save many redundant types. With this article, I will explain how TypeScript supports Duck Typing.

But what is Duck Typing in first place?

In other words, don’t check whether it IS-a duck: check whether it QUACKS-like-a duck, WALKS-like-a duck, etc, etc, depending on exactly what subset of duck-like behaviour you need to play your language-games with. — Alex Martelli

For more information about Duck Typing do read the Wikipedia article.

Now back to TypeScript, take a look at following interface IItem

interface IItem 
{
id: number,
title: string
};
function print(item: IItem)
{
console.log(item.id + " > " + item.title);
}
var i : IItem = {
id: 10,
title : "ABC"
};
//Ok - As it implements IItem
print(i);
//Ok - As it implicitly implements IItem
print({ id: 11, title: "XYZ" });

The print function expects a parameter of type IItem interface, the variable i is of type IItem, and it works as expected. The second example, which also calls the print function with an parameter which implicitly implements IItem, and that works too.

Now comes the Duck Typing

interface IProduct
{
id: number,
title: string,
author: string
};
var book: IProduct = {
id: 1,
title: "C# in Depth",
author: "Jon Skeet"
};
//Ok - Even though book implements IProduct and not the IItem
//It has two properties "id" and "title"
//which is actually the print function is interested in
print(book);

So, here the book variable, does not implement IItem, but does have two properties “id” and “title” and it works too.

So to summarize, the print function is actually interested if the parameter has two properties “id” and “title” (whether its quack and walk) and not to check if it really if it implements IItem or not.

And that’s what they call it as Duck Typing.

Try this sample in TypeScript playground.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (3)

Write a response