This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

preface

In the previous article, we looked at the basic types of TS, which include enum, never, void, and so on, in addition to the data types provided in JS. In this chapter, we will explore advanced types in TS.

Cross type

Crossover typing is the merging of multiple types into a single type. For example, when the abstraction of an interface is extremely small, we need to use mixins patterns when implementing an object

function extend<T.U> (first: T, second: U) :T & U {
    letresult = <T & U>{}; for (let id in first) { (<any>result)[id] = (<any>first)[id]; } for (let id in second) { if (! result.hasOwnProperty(id)) { (<any>result)[id] = (<any>second)[id]; } } return result; } class Person { constructor(public name: string) { } } interface Loggable { log(): void; } class ConsoleLogger implements Loggable { log() { // ... } } var jim = extend(new Person("Jim"), new ConsoleLogger()); var n = jim.name; jim.log();Copy the code

Here’s an example of the official website, where we call extend, and we mix the ConsoleLogger class into the Person class.

The joint type

Union types have many similarities to the crossover types we just mentioned, but they are different in how they are used.

Usually when we write Vue or React, we have a control CSS request, and when we encounter a width, we can use a numeric type, we can also use a string type, like this:

function setWidth(id:string, width: any) {
    if (typeof width === 'string') {
        return `${id}: ${width}`
    }
    if (typeof width === 'number') {
        return `${id}: ${width}px`
    }
    return new Error('error')}Copy the code

For example, if we pass an object, we should report an error. However, if we write any, we cannot report an error during TS checking. So, we use the union type to change it.

function setWidth(id:string, width: string | number) {
    if (typeof width === 'string') {
        return `${id}: ${width}`
    }
    return `${id}: ${width}px` // Must be of type number
}
Copy the code

Since only number and string are identified for the type passed in, the judgment can also be reduced.

A union type indicates that a value can be one of several types. We use a vertical bar (|) separated for each type, so the number | string | Boolean said a value can be a number, a string, or Boolean.

Type protection and type differentiation

Having a union type also introduces some new problems, because uncertainty about the type of the value passed in requires the value to be judged before the operation.

Using the type assertion mechanism is an explicit way of telling the TS inspector that I know exactly what type is here, trust me.

let pet: Fish | Bird = getSmallPet();

if ((<Fish>pet).swim) { 
    (<Fish>pet).swim();
}
else {
    (<Bird>pet).fly();
}
Copy the code

In JS, typeof, instanceof and other keywords are provided to determine the type. Similarly, in TS, these keywords can be used to protect the type.

Type the alias

Type aliases allow us to have some type definitions that are closer to business semantics, like giving a new name to a type. Similar to the interface, but can work with raw values, union types, tuples, and anything else you need to write by hand. Let’s look at the code:

type Name = string;
type NameResolver = () = > string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver) :Name {
    if (typeof n === 'string') {
        return n;
    }
    else {
        returnn(); }}Copy the code

Type aliases are used in much the same way as interfaces. For beginners, use interfaces where interfaces can be used and type aliases where interfaces cannot be used.

summary

This chapter mainly introduces the cross types, joint type, such as advanced type, also tells the story of how to do the type of protection and distinguish types, in the actual development, we can do it according to the properties of the TS to provide flexible use, also has a lot of similarities between features, we need to combine the actual business scenarios, do reasonable use.