Home >Web Front-end >CSS Tutorial >Demystifying TypeScript Discriminated Unions

Demystifying TypeScript Discriminated Unions

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-03-14 10:57:09955browse

Demystifying TypeScript Discriminated Unions

TypeScript is a powerful tool for building scalable JavaScript applications and has almost become the standard for large Web JavaScript projects. However, for newbies, TypeScript also has some tricky things, one of which is distinguishing between union types.

Consider the following code:

 interface Cat {
  weight: number;
  whiskers: number;
}
interface Dog {
  weight: number;
  friendly: boolean;
}
let animal: Dog | Cat;

Many developers will be surprised to find that when accessing animal , only weight attribute is valid, while whiskers and friendly attributes are invalid. This article will explain the reasons.

Before we dive into it, let's quickly review structural and nominal types, which will help understand TypeScript's distinction between union types.

Structure type

The best way to understand structural types is to compare them with nominal types. Most of the typed languages ​​you may have used are nominally typed. For example, C# code (Java or C similar):

 class Foo {
  public int x;
}
class Blah {
  public int x;
}

Even if Foo and Blah have exactly the same structure, they cannot assign values ​​to each other. The following code:

 Blah b = new Foo();

The following error will be generated:

<code>无法隐式转换类型“Foo”为“Blah”</code>

The structure of these classes does not matter. A variable of type Foo can only be assigned to an instance of Foo class (or its subclass).

TypeScript, on the contrary, adopts structure types. TypeScript considers them compatible if both types have the same structure.

Therefore, the following code works fine:

 class Foo {
  x: number = 0;
}
class Blah {
  x: number = 0;
}
let f: Foo = new Blah();
let b: Blah = new Foo();

A collection of types as matching values

Let's explain this further. Given the following code:

 class Foo {
  x: number = 0;
}

let f: Foo;

f is a variable that can hold any object that is the same structure as Foo class instance, in this case, which means an x property representing a number. This means that even a normal JavaScript object can be accepted.

 let f: Foo;
f = {
  x: 0
};

Union Type

Let's go back to the code at the beginning of this article:

 interface Cat {
  weight: number;
  whiskers: number;
}
interface Dog {
  weight: number;
  friendly: boolean;
}

We know:

 let animal: Dog;

Make animal any object with the same structure as the Dog interface. So what does the following code mean?

 let animal: Dog | Cat;

This defines the animal type as any object that matches the Dog interface, or any object that matches the Cat interface.

So why does animal now only allow us to access weight attribute? Simply put, it is because TypeScript doesn't know what type it is. TypeScript knows animal must be Dog or Cat , but it may be either. If we are allowed to access the friendly property, but in the instance animal is actually Cat and not Dog , it may result in a runtime error. The same is true for whiskers attribute.

Union type is a union of valid values, not a union of attributes. Developers often write code like this:

 let animal: Dog | Cat;

And expect animal to have a union of Dog and Cat properties. But this is another mistake. This specifies animal has a value that matches a joint of valid Dog and valid Cat values. But TypeScript only allows you to access properties it knows exists. Currently, this means all types of properties in the union.

Type narrowing

Now, we have:

 let animal: Dog | Cat;

When animal is Dog , how do we correctly treat it as Dog and access properties on the Dog interface, and also handle it when it is Cat ? Currently, we can use the in operator. This is an old JavaScript operator that you may not see very often, which allows us to test whether a property exists in an object. For example:

 let o = { a: 12 };

"a" in o; // true
"x" in o; // false

It turns out that TypeScript is deeply integrated with the in operator. Let's see how to use:

 let animal: Dog | Cat = {} as any;

if ("friendly" in animal) {
  console.log(animal.friendly);
} else {
  console.log(animal.whiskers);
}

This code will not produce errors. Within the if block, TypeScript knows that there is a friendly property, so converts animal to Dog . Within the else block, TypeScript similarly treats animal as Cat . You can even view this in the code editor by hovering your mouse over an animal object in these blocks.

Distinguishing union types

You might expect the blog post to end here, but unfortunately, narrowing the union type is very limited by checking if the attribute exists. It works well for our simple Dog and Cat types, but when we have more types and more overlap between these types, things can easily get more complex and fragile.

This is where differentiating the union type comes in handy. We will keep everything from before, just add a property to each type, whose only purpose is to distinguish (or "differentiate") these types:

 interface Cat {
  weight: number;
  whiskers: number;
  ANIMAL_TYPE: "CAT";
}
interface Dog {
  weight: number;
  friendly: boolean;
  ANIMAL_TYPE: "DOG";
}

Note the ANIMAL_TYPE attribute on both types. Don't mistake it for a string with two different values; this is a literal type. ANIMAL_TYPE: "CAT"; represents a type that happens to contain the string "CAT", that's it.

Now our inspection has become more reliable:

 let animal: Dog | Cat = {} as any;

if (animal.ANIMAL_TYPE === "DOG") {
  console.log(animal.friendly);
} else {
  console.log(animal.whiskers);
}

This check will be foolproof assuming that each type participating in the union has a different value of the ANIMAL_TYPE attribute.

The only downside is that you now need to deal with a new property. Each time an instance of Dog or Cat is created, you must provide the unique correct value for ANIMAL_TYPE . But don't worry about forgetting, because TypeScript will remind you. ?

Further reading

If you want to learn more, I recommend reading the TypeScript documentation on type narrowing. This will give us a more in-depth look at what we are discussing here. There is a section on type assertions in this link. These allow you to define your own custom checks to narrow the types without using type discriminators or relying on the in keyword.

in conclusion

At the beginning of this article, I said, in the following example, why weight is the only accessible property:

 interface Cat {
  weight: number;
  whiskers: number;
}
interface Dog {
  weight: number;
  friendly: boolean;
}
let animal: Dog | Cat;

What we learned is that TypeScript only knows animal can be Dog or Cat , but not both. Therefore, we can only get weight , which is the only public property between the two.

The concept of distinguishing union types is the way TypeScript distinguishes these objects, and this approach is very scalable, even for larger collections of objects. Therefore, we have to create a new ANIMAL_TYPE property on both types that holds a single literal value that we can use to check. Of course, this is another thing that needs to be tracked, but it also produces more reliable results – which is exactly what we want from TypeScript in the first place.

The above is the detailed content of Demystifying TypeScript Discriminated Unions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn