This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

The joint type

A union type is an or operation of a type.

Let’s look at this example:

let seven: number;

seven = 7;

seven = 'Seven'; Error: Cannot assign type "Seven" to type "number"
Copy the code

The above code will report an error. Of course we’ll change it to any, but it’s better to use the union type

let seven: number | string;

seven = 7;

seven = 'Seven'; 
Copy the code

With federated types, you can access only properties and methods that are common to both types, as shown in the figure below.

Problem: is a variableanimalDeclare the appropriate union type

let animal: _____;
animal = 'panda';
animal = 10;
animal.valueOf(0);
Copy the code

A. number | string

B. number | undefined

C. string | undefined

D. undefined | null

parsing

We need to declare the appropriate variable for Animal. Let’s first analyze the following operation:

animal = 'panda';
animal = 10;
Copy the code

This two-step operation requires animal to declare either string or number.

animal.valueOf();
Copy the code

The valueOf method is common to string, number, and Boolean. Therefore, choose A.

Types of assertions

A type assertion is the assertion that it must be of this type.

Let’s look at this example:

let seven: number | string;

seven.toFixed(3);

seven.length;

seven.toString();
Copy the code

If you run the above code, you will get an error. What if we rewrite the code so it doesn’t report errors?

You can use AS for type assertion.

let seven: number | string;

(seven as number).toFixed(3);
// Assert a string
(seven as string).length;

seven.toString();
Copy the code

Exercise: Which of the following describes an error about a type assertion?

A. Type assertion can specify A variable of A combined type as A more specific type

B. You cannot assert that a union type does not exist

C. Type assertion is a type conversion.

TypeScript’s type system is a helper tool that doesn’t dictate the logic of our code, but does its best to give us the type back, so it’s not a type conversion. So choose C.

Data: Two grammars for type assertion

We’ve seen how to use type assertions to predict the type of a value and thus access its attributes, so let’s look at the following code.

let seven: number | string;

(seven as number).toFixed(3); // The first syntax for type assertion

<string>seven.length; // Second syntax for type assertion
Copy the code

All of the above code compiles because it follows the canonical type assertion syntax.

One thing to note here is that if you write JSX code in TypeScript, you cannot use

seven. Length as an assertion because < > is recognized as JSX syntax.

Data: asserts to be of type any

You might wonder, why assert type any? I thought we were trying to make the type explicit.

There is no conflict here; to keep your code clear and readable, it is important to avoid declaring any when developing with TypeScript. However, in the real world of development, there are situations where TypeScript does not compile. Here are two examples.

When a method is called, the actual parameter passed may be a more specific value

Let’s look at the following code:

function handler (e: Event) {
    let touchEvent = e as TouchEvent;
}
Copy the code

The above code will compile, but the following code will report an error

function handler (e: Event) {
    let $element = e as HTMLElement; // Type "Event" cannot be converted to type "HTMLElement". The attribute "accessKey" is missing from type "Event".
}
Copy the code

Here we expect $Element to be a DOM element, so TS attempts to see if e has the required attributes of a DOM element. The first access is the accessKey attribute, because e is of type Event.

If we need to enforce a declaration, we might want to assert the value as any, something like this:

function handler (e: Event) {
    let $element = e as any as HTMLElement; // Double assertion
}
Copy the code

This can also be interpreted as a double assertion, which finally passes compilation.

Introducing third party libraries that fail to compile

In a hypothetical scenario where we introduce an older version of the HTML2Canvas library that binds the html2Canvas function to a Windows object, our usage might be as follows:

import './html2canvas';

let $element = document.body;

window.html2canvas($element, canvas= > {
    console.log(canvas.toDataURL());
}); // Html2canvas does not exist on type "Window"
Copy the code

At this point we can assert the window as any to avoid compile failures

import './html2canvas';

let $element = document.body;

(window as any).html2canvas($element, canvas= >{
    console.log(canvas.toDataURL());
});
Copy the code