This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Examples of TypeScript
TypeScript associates types and type protection.Copy the code
The joint type
Joint type (Union Types) said values can be one of many Types, joint type using | separated for each type. Union types have been used in previous examples, so I’ll explain them in detail separately.
/ / 1
// Define a variable
let myNumber: number | string;
myNumber = 10;
myNumber = 'ten';
Copy the code
Example 1 uses the union type for the variable myNumber, which can be either number or string.
/ / 2
/ / declare the interface
interface Teacher {
name: string;
profession: 'teacher';
teach: () = > {};
}
interface Dancer {
name: string;
profession: 'dancer';
dance: () = > {};
}
function work(person: Teacher | Dancer) {
person.name / / normal
person.teach(); / / an error
person.dance(); / / an error
}
Copy the code
Example 2 declares two interfaces, Teacher and Dancer, and uses the union type for work(). We find that the name attribute works fine when using union types, but the teach() or dance() method returns an error. Why?
Because the name attribute is shared by both Teacher and Dancer, and the teach() or dance() methods are unique to Teacher or Dancer, there is no guarantee that they will exist on work().
As you can see, the same problem can occur with union types. To avoid these problems and keep the code rigorous, we need to do type protection. There are many ways to implement type protection, but let’s take two common examples.
Type of protection
Method 1: Implement type protection through type assertion
/ / 3
function work(person: Teacher | Dancer) {
if (person.profession === 'teacher') {
// If person's profession is a teacher, we assert to TypeScript that person is a teacher
(person as Teacher).teach()
} else {
(person as Dancer).dance()
}
}
Copy the code
Method 2: Implement type protection through in syntax
/ / 4
function work(person: Teacher | Dancer) {
// Call the teach method on person
if ('teach' in person) {
person.teach();
} else{ person.dance(); }}Copy the code
We can see that TypeScript is smart because the work() function has only Teacher and Dancer parameters.
You can also implement type protection through typeof syntax, instanceof syntax, and so on, but I won’t give you any examples here.
Finish this! If this article helps you at all, please give it a thumbs up.