The use of type aliases and string literal types and tuples in typeScript

Table of contents

1. Type aliases

 2. String literal type

3. Tuple


1. Type aliases

Type aliases are often used with union types.

We  type create type aliases using, for example:

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

 2. String literal type

The string literal type is used to constrain the value to be only one of several strings, for example:

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
    // do something
}

handleEvent(document.getElementById('hello'), 'scroll');  // 没问题
handleEvent(document.getElementById('world'), 'dblclick'); // 报错,event 不能为 'dblclick'

// index.ts(7,47): error TS2345: Argument of type '"dblclick"' is not assignable to parameter of type 'EventNames'.

 In the above example, we use  type a string literal type  EventNames, which can only take one of the three strings.

Note that both type aliases and string literal types are  type defined using .

3. Tuple

 Arrays combine objects of the same type, while tuples combine objects of different types .

Tuples originated in functional programming languages ​​such as F#, where tuples are used frequently.

 Define a pair of tuples whose values ​​are  string and  :number

let tom: [string, number] = ['Tom', 25];

When assigning or accessing an element with a known index, the correct type is obtained:

let tom: [string, number];
tom[0] = 'Tom';
tom[1] = 25;

tom[0].slice(1);
tom[1].toFixed(2);

You can also assign only one of them:

let tom: [string, number];
tom[0] = 'Tom';

However, when directly initializing or assigning values ​​to variables of the tuple type, all items specified in the tuple type need to be provided.

let tom: [string, number];
tom = ['Tom', 25];
let tom: [string, number];
tom = ['Tom'];

// Property '1' is missing in type '[string]' but required in type '[string, number]'.

Out of bounds elements

When an out-of-bounds element is added, its type is restricted to the union type of each type in the tuple:

let tom: [string, number];
tom = ['Tom', 25];
tom.push('male');
tom.push(true);

// Argument of type 'true' is not assignable to parameter of type 'string | number'.

In this example, only string and number types can be added, and an error will be reported if adding Boolean type. 

Guess you like

Origin blog.csdn.net/qq_57423665/article/details/130639373