27 Nov 2022

Duck Typing

I was going through a TypeScript lesson on Object Narrowing, and one of the takeaways was that object narrowing is a way to achieve Structural Typing, and that this is also known as Duck Typing as in the following example:

type User = { email: string, admin: boolean };

let ichigo: User = {
  email: '[email protected]',
  admin: true

function sendEmail({email}: {email: string}): string {
  return email;

The function sendEmail is Structurally Typed, or apparently, Duck Typed as per the lesson’s note:

Structural typing is also sometimes called “duck typing”. This term is a reference to a saying: “If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”

In programming, “duck typing” means that we only care about the properties we’re accessing, and we don’t care whether the object has extra properties.

Another article gave the technical definition as:

Duck Typing is a way of programming in which an object passed into a function or method supports all method signatures and attributes expected of that object at run time. The object’s type itself is not important. Rather, the object should support all methods/attributes called on it.

Useful for ensuring object properties can be worked with as a subset of the larger object, and also for qualifying the traits of numerous species of waterfowl in the family Anatidae.

#TIL #TheMoreYouKnow

Webmentions & Comments

Copyright © Paramdeo Singh · Built with Jekyll in 🇬🇾 · All Rights Reserved

this node is permanently morphing last updated on 26 Dec 2022

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #TIL