“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

preface

We know that TS is a superset of JS, which will eventually compile into JS. TS is much more than JS. In the previous article, we introduced the types that both TS and JS have. Today we will take a look at the types that are unique to TS

First, the any type of “famous”

Any type

A variable of type Any can be assigned a value of Any type

let any1: any = 'xxx'
Copy the code

The type of void

Void is used to return null

In the following example, no response is returned

function fn() :void{
    console.log('This is a fn,but return is void')}Copy the code

Enum type

Enum Indicates the enumeration type. It can be interpreted as declaring a special type using the enum keyword, for example:

enum Direction {
  NORTH,
  SOUTH,
  EAST,
  WEST,
}

let dir: Direction = Direction.NORTH;
Copy the code

Declare a type by type

TS provides some basic types, and classes can also be used as types. But sometimes we need something more flexible, which means we need to customize some types or type declarations

Declaring a type requires the keyword type for example

type User = {
    name: string; age? :number;
}
Copy the code

The above code defines a User type that must have a name attribute of type string and optionally an age attribute of type number

let user: User;
user = {
    name: 'Alice'
}
Copy the code

In the above code, declaring a user variable requires that we define the user type and assign it a value corresponding to the defined type

Not just for variables, of course. Custom types, just like normal types, can be used anywhere a type can be used, with no restrictions, such as function parameters and so on

function show(obj: User) {
    console.log(obj.name)
}
show(user);
Copy the code

You can see how easy it is to create a new type using the type keyword

Tuple Type of a tuple

The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type

let x: [string.number];
x = ['hi'.1];
Copy the code

Never type

The never type represents the types of values that never exist

Like some function of an unattainable endpoint

function error(message: string) :never {
    throw new Error(message);
}
Copy the code

An array type

Represents an array as follows:

let list: number[] = [1.2];
Copy the code

Generic array

Generic arrays are like array types, except in a different format. For example, the list array above is written as a generic, as follows:

let list: Array<number> = [1.2];
Copy the code

conclusion

We’ve covered a number of types that are unique to TS, but there are several, such as the Object and {} types mentioned in the previous article, and the fact that all classes in TS can be used as types

That’s all for this article. Any omissions are welcome!