TypeScript and Duck Typing

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" });
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);

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

[Tutorial] Custom Form Controls with Angular

How to Setup and Start learning React Native

Angular patterns 3: flexible and scalable design of complex pages

React from Beginner to Expert without CRA

Mocking AWS Services — the easy way

Vite — witnessing the next-gen frontend tooling (Part-1)

Unit Test in React with Jest — Enzyme

Create a beautiful select using Contrast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ajay Bhosale

Ajay Bhosale

More from Medium

How does Typescript work?

Building Search from Scratch in TypeScript: Part 1

Advanced Typescript: Depth control of recursive structures

Infinity. Photo by Ryan Stone

TypeScript 4  — Introduction