← Back
lang type-guard typescript

Type inference with "in" operator

It's quite common in Typescript to have this kind of code:

interface Cat {
meow(): void
}

interface Human {
hello(): void
}

function talk(animal: Cat | Human) {
if (/* it is a cat */) {
animal.meow()
} else {
animal.hello()
}
}

You can try something like this:

function talk(animal: Cat | Human) {
if (typeof animal.meow === "function") {
...
}
}

But won't work because you're trying to access "meow" before testing the type.

The standard solution is to use a typescript type guard function. Among other things, it's quite verbose.

I've just learned a better one: the javascript "in" operator:

function talk(animal: Cat | Human) {
if ("meow" in animal) {
animal.meow();
} else {
animal.hello();
}
}

🖖