weakty

Today was once of those days where a programming concept that I’d heard of several times was made clear. A few weeks ago I signed up for a year of Execute Program using a lingering work budget. My hope was to improve my understanding of typescript (and python, since EP just released a python course, too).

I’m about halfway through the TypeScript Basics course and am getting to the good stuff. The lesson "Object Narrowing" explains Narrowing and Structural typing in TypeScript, and at the end explains that this is also referred to as Duck Typing.

I feel a little bit bad just copying and pasting this lesson from Execute Program, but I’ll just grab of an example from it to demonstrate what duck typing is:

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

let amir: User = {email: 'amir@example.com', admin: true};

function sendEmail({email}: {email: string}): string {
  return `Emailing ${email}`;
}

[
  sendEmail(amir),
  sendEmail({email: 'betty@example.com'}),
];

Result:

['Emailing amir@example.com', 'Emailing betty@example.com']

In this example, the sendEmail function has an inline type definition — where it only cares that the property email is present. As far as I understand, this means you could pass in an object with any number of properties in it—so long as one of them is email, the function will not through a type error.

I remember coming across the term duck typing several times, and seeing the idiom: if it walks like a duck, talks like a duck, .. it’s probably a duck (etc) referenced years ago. Never clicked. Why? I only really started writing typed languages (well, aside from Elm, a few years ago) recently. A testament to my brain’s ability to background the unimportant, I guess.

At this point in my programming journey this isn’t exactly a revelation—but what is worth noting is that feeling of finally encountering a definition / example and having it click. It’s worth calling out.