Type the alias

An alias, as the name suggests, is a new name for a type that is easy to remember and use. The following examples will help you understand and apply them.

// alias.ts
type Name = string;
type ShowName = (a)= > string; // Typescript =>
type NameOrShowName = Name | ShowName; // Union type

const getName = (name: NameOrShowName) = > { // ES6 =>
    if(typeof name === 'string') {return name;
    } else {
        returnname(); }}let showName = (a)= > 'pr is a boy';

console.log(getName('pr')); // pr
console.log(getName(showName())); // pr is a boy
Copy the code

Note: Don’t confuse => in TypeScript with => in ES6

In TypeScript type definitions, => is used to represent function definitions, with input types enclosed in parentheses on the left and output types on the right.

In ES6, => is called the arrow function;

Of course, Typescript does use arrow functions, but this is to illustrate the difference;

Findings:

1. Use keyword type to create an alias.

2. Using an alias is usually used in the scenario of the association type.

String literal type

It is used to constrain values from defined fields only.

// string.ts
type EventNames = 'click' | 'scroll' | 'mousemove';
const handleEvent: (a: Element, b: EventNames) = > string = (ele: Element, event: EventNames) = > {
    return `${ele} ${event}`;
}

handleEvent(document.getElementById('header'), 'scroll');
handleEvent(document.getElementById('footer'), 'keyup');

// 0.1.1/string.ts: 7:48-error TS2345: Argument of type '"keyup"' is not assignable to parameter of type 'EventNames'.
    // 7 handleEvent(document.getElementById('footer'), 'keyup');  
Copy the code

This error is reported because keyUp is not in EventNames.

Findings:

Type aliases and string literal types are defined using type.

This code Github

You can…

Previous: Typescript classes and interfaces

Next: Typescript generics

Contents: A primer to Typescript’s short book