国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Structure type
A collection of types as matching values
Union Type
Type narrowing
Distinguishing union types
Further reading
in conclusion
Home Web Front-end CSS Tutorial Demystifying TypeScript Discriminated Unions

Demystifying TypeScript Discriminated Unions

Mar 14, 2025 am 10:57 AM

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>無(wú)法隱式轉(zhuǎn)換類型“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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

See all articles