TypeScript common types

catalogue

1. Type notes

2. Common foundation types

1. Existing JavaScript types

2. New typescript type

3. Original type

4. Array type

1. Writing method of type [], such as

2. The writing method of array < type >, such as

5. Joint type

6. Type alias

7. Function type

void type

Function optional parameters

8. Object type

Use type alias

Type of method with parameters

Method type in the form of arrow function

Object optional properties

9. interface

Difference between interface and custom type

Interface inheritance

10. Tuple

11. Type inference

12. Literal type

Usage scenarios and modes

13. Enumeration

Numeric enumeration

String Enum

Enumeration implementation principle

14. any type

15. Type assertion

16. typeof 

TypeScript is a superset of JS. TS provides all the functions of JS and adds an additional type system

JS has types (for example, number/string, etc.), but JS will not check whether the type of variables has changed, while TS will check

The main advantage of TypeScript type system: it can show and mark unexpected behavior in code, thus reducing the possibility of errors

1. Type notes

Sample code

let age: number = 18;

Note: in the code: number is the type annotation

The type annotation restricts that only the value of this type can be assigned to this variable

Error demonstration

// Error reason: the value of string type is assigned to the variable of number type, and the types are inconsistent
let age: number = '18';

2. Common foundation types

Common foundation types in TS can be divided into two categories

1. Existing JavaScript types

  • Original type: number/string/boolean/null/undefined/symbol
  • Object type: object (array, object, function, etc.)

2. New typescript type

  • Union type, user-defined type (type alias), interface, ancestor, literal type, enumeration, void, any, etc

Note: the original type is written in the same way in TS and JS, and the object type is more detailed in TS. each specific object has its own type syntax

3. Original type

number/string/boolean/null/undefined/symbol

Features: it can be written completely according to the name in JavaScript

let age: number = 18;
let username: string = 'Zhang San';
let isMerry: boolean = false;
let unique: Symbol = Symbol('shuiruohanyu');

4. Array type

Two ways to write arrays

1. Writing method of type [], such as

let userList: string[] = ['John', 'Bob', 'Tony'];
let peopleList: object[] = [{ name: 'Zhang San', age: 18 }];

2. The writing method of array < type >, such as

let user2List: Array<string> = ['John', 'Bob', 'Tony'];
let people2List: Array<object> = [{ name: 'Zhang San', age: 18 }];

5. Joint type

There are both number type and string type in the array. How should the type of this array be written?

You can use | (vertical line) to split multiple types, such as

let str: string | number = 1;
str = 'Zhang San';

If the array can be a string or a number, it can be written like this

let arr: Array<number | string> = [1, 2, 'Zhang San'];

6. Type alias

When a complex type or union type is too many or frequently used, the use of the type can be simplified through the type alias

Usage: type = name = specific type

type CustomArray = Array<number | string>;
let arr1: CustomArray = [1, 2, 'Zhang San'];

In the above code, type is used as the keyword to create a custom type

  • Type aliases can make any valid variable name
  • Recommended nomenclature of the big hump

7. Function type

In addition to variables, our common type assignments include type declarations for functions

Function types need to refer to the types of} function parameters and return values. There are two ways to write them here

  • The first method: specify parameters separately and return value type
// Specify the function return value and function parameters separately
function add(num1: number, num2: number): number {
  return num1 + num2;
}
// Specifies the form of the variable
const add2 = (num1: number, num2: number): number => {
  return num1 + num2;
};
  • Second, specify both parameters and return values
// Specify both parameters and return values

type CustomFunc = (num1: number, num2: number) => number;

const add3: CustomFunc = (num1, num2) => {
  return num1 + num2;
};

Note: when a function is used as an expression, you can add types to the function through a syntax similar to the form of arrow function, which is only applicable to function expressions

void type

When our function is defined as a type with no return value, it can be represented by the keyword void

// Function with no return value

type CustomFunc1 = (num1: string, num2: number) => void;

const combinStr: CustomFunc1 = () => {};

If a function does not return a value, in this case, in the type of TS, you should use the "void" type

const add4 = () => {};
// If nothing is written, it means that the type of add4 function is void

const add5 = (): void => {};
// This method explicitly specifies that the return value is void, which is the same as the type above

const add6 = (): undefined => {
  return undefined;
};
// If the specified return value is undefined, return undefined

Function optional parameters

When we define a function, some parameters can be passed or not. In this case, the optional parameters of TS can be used to specify the type

For example, when using the slice method of array, we can directly use slice() or pass in the parameter slice(1) or slice(1,3)

const slice = (start?: number, end?: number): void => {};

 ? Indicates whether the parameter or variable can be passed or not

Note: optional parameters can only appear at the end of the parameter list, that is, they must precede the optional parameters

8. Object type

The object in JS is composed of attributes and methods, and the object type of TS is the description of attributes and methods in the object

Writing method

// If there are multiple attributes, you can wrap and remove the interval symbol

let person3: {
  name: string;
  sayHello: Function;
} = {
  name: 'Wang Wu',
  sayHello() {},
};

Summary: but use {} to describe the object structure

The attribute takes the form of attribute name: type

The Function can take the form of {method name (): return value type} or} Function name: Function (no return value specified)

Use type alias

Using {} directly will reduce the readability of the code and have no recognition. It is more recommended to use type alias to add object type

type PersonObj = {
  name: string;
  sayHello(): string;
};

const p1: PersonObj = {
  name: 'Gao dada',
  sayHello() {
    return this.name;
  },
};

Type of method with parameters

If the function in the object has parameters, you can specify the parameter type in the function

// Function method with parameters

type PersonObj2 = {
  name: string;
  sayHello(start: number): string;
};

const p2: PersonObj2 = {
  name: 'Gao dada',
  sayHello(start) {
    return this.name;
  },
};

Method type in the form of arrow function

// Arrow function type definition
type People = {
  sayHello: (start: number) => string;
};
const p3: People = {
  sayHello() {
    return '';
  },
};

Object optional properties

Some attributes in the object are sometimes optional. At this time, we can still use? To show

type Config = {
  method?: string;
  url: string;
};

const func = (config: Config) => {};
func({ url: '/a' });

9. interface

When an object type is used many times, interface is generally used to describe the type of object to achieve the purpose of reuse

  • We use the interface keyword to declare the interface
  • It is recommended that the interface name start with I
  • After the interface variable is declared, it is directly used as the name of the interface

Semicolon is not required after interface

// Interface

interface IPeople {
  name: string;
  age: number;
  sayHello(): void;
}

let p: IPeople = {
  name: 'fairly tall',
  age: 18,
  sayHello() {},
};

Difference between interface and custom type

Same point: all objects can be assigned a type

Difference: the interface can only specify the type for the object, and the type alias can specify the alias for any type

  • type is recommended

Interface inheritance

  • If there are the same attributes and methods between two interfaces, the common attributes and methods can be separated and reused through inheritance

For example, both interfaces have x and y attributes, which can be repeated twice, but it is very cumbersome

interface Point2D {
  x: number;
  y: number;
}
interface Point3D {
  x: number;
  y: number;
  z: number;
}
  • Better way
interface Point2D { x: number; y: number }
interface Point3D extends {
    z: number
}

We use the extends keyword to implement Point3D, which inherits the definitions of all the attributes of Point2D, and has inherited attributes and self-defined attributes at the same time

10. Tuple

When we want to define the type of specific index position in an array, we can use Yuanzu.

The original array mode can only broadly define the common types in the array, and cannot be accurate to the position

A tuple is another type of array that knows exactly how many elements it contains and the type corresponding to a particular index

let position: [number, number] = [39.5427, 116.2317];

11. Type inference

In TS, the type inference mechanism of TS will help provide types in some places where the type is not clearly indicated

In other words, due to the existence of type inference, type annotations can be omitted in some addresses.

  • Common scenarios where type inference occurs
  1. When a variable is declared and initialized
  2. When determining the return value of a function
// Variable Creator_ Name is automatically inferred as a string
let creater_name = 'gaoly';

// The type of the return value of the function is automatically inferred as number
function addCount(num1: number, num2: number) {
  return num1 + num2;
}

Recommendation: omit the type annotation where it can be omitted (lazy, make full use of the ability of TS type inference to improve development efficiency)

Tip: if you don't know the type, you can use the prompt of VSCode to view the type by placing the mouse over the variable name

12. Literal type

What are the following code types?  

// Literal type

let str1 = 'Zhang San';
const str2 = 'Zhang San';

The answer can be obtained through the type derivation of TS

1. The variable type of the variable str1 is: string

2. The variable type of variable str2 is' Zhang San '

Explanation: str1 is a variable (let) whose value can be any string, so the type is: string

str2 is a constant (const). Its value cannot be changed. It can only be 'Zhang San'. Therefore, its type is: 'Zhang San'

At this time, 'Zhang San' is a literal type, that is, a special string can also be used as a type in TS

Any JS literal (object, array, number) can be used as a type

Usage scenarios and modes

  • Usage mode: literal type is used together with union type
  • Usage scenario: used to represent a clear list of optional values
  • For example, in the greedy Snake game, the optional value of the direction of the game can only be any one of up, down, left and right
type Direction = 'left' | 'right' | 'up' | 'down';

// Use custom type:

function changeDirection(direction: Direction) {
  console.log(direction);
}

// When calling a function, there will be a type prompt:
changeDirection('up');
  • Explanation: the value of the parameter direction can only be any one of up/down/left/right
  • Advantages: compared with string type, literal type is more precise and rigorous

13. Enumeration

  • The function of enumeration is similar to the function of literal type + union type combination, and can also represent a set of explicit optional values
  • Enumeration: defines a set of named constants. It describes a value that can be one of these named constants
// enumeration

// Create enumeration
enum Direction2 {
  Up,
  Down,
  Left,
  Right,
}

// Use enumeration type
function changeDirection2(direction: Direction2) {
  console.log(direction);
}

// When calling the function, you need to pass in: enumerate any one of the Direction members
// Similar to the object in JS, it directly passes through the point (.) Syntax access enumeration members
changeDirection2(Direction2.Up);

Numeric enumeration

  • Question: we take the enumeration member as the argument of the function. What is its value?
  • Explanation: by moving the mouse into direction Up, you can see that the value of the enumeration member up is 0
  • Note: enumeration members have values. The default value is a value that increases automatically from 0
  • We call the enumeration in which the value of an enumeration member is a number: numeric enumeration
  • Of course, you can also initialize values for members in the enumeration
// Down -> 11,Left -> 12,Right -> 13
enum Direction {
  Up = 10,
  Down,
  Left,
  Right,
}

enum Direction {
  Up = 2,
  Down = 4,
  Left = 8,
  Right = 16,
}

String Enum

  • String enumeration: the value of an enumeration member is a string
  • Note: String enumeration has no self growth behavior. Therefore, each member of string enumeration must have an initial value
enum Direction {
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT',
}

Enumeration implementation principle

  • Enumeration is one of the few non JavaScript type level extensions (not just types) in TS
  • Because: other types are only treated as types, while enumerations are not only used as types, but also provide values (enumeration members have values)
  • In other words, other types will be automatically removed when compiled into JS code. However, enumeration types are compiled into JS code
enum Direction {
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT'
}

// Will be compiled into the following JS code:
var Direction;

(function (Direction) {
  Direction['Up'] = 'UP'
  Direction['Down'] = 'DOWN'
  Direction['Left'] = 'LEFT'
  Direction['Right'] = 'RIGHT'
})(Direction || Direction = {})
  • Note: enumeration is similar to the function of literal type + union type combination mentioned earlier. It is used to represent a clear list of optional values
  • In general, the combination of literal type and union type is recommended, because it is more intuitive, concise and efficient than enumeration

14. any type

  • Principle: any is not recommended! This will turn TypeScript into "AnyScript" (losing the advantage of TS type protection)
  • Because when the value type is any, you can perform any operation on the value without code prompt
let obj: any = { x: 0 };

obj.bar = 100;
obj();
const n: number = obj;
  • Explanation: the above operations will not have any type of error prompt, even if there may be errors
  • Avoid using any type as much as possible, unless you temporarily use any to "avoid" writing long, complex types
  • Other situations that implicitly have any type
    1. Declared variables do not provide types or default values
    2. Function arguments are not typed
  • Note: since any is not recommended, type should be provided in both cases

In project development, use any type as little as possible

15. Type assertion

Sometimes you will specify the type of a value more clearly than TS. at this time, you can use type assertion to specify a more specific type. For example,

const aLink = document.getElementById('link');
  • Note: the type of the return value of this method is HTMLElement. This type only contains the properties or methods common to all tags, and does not contain the href and other properties unique to a tag
  • Therefore, this type is too broad (not specific) to operate on properties or methods unique to a tags such as href
  • Solution: in this case, you need to use type assertions to specify more specific types
  • Use type assertions:
const aLink = document.getElementById('link') as HTMLAnchorElement;
  • Explanation:

    1. Use the # keyword to implement type as sertions
    2. The type after the keyword as is a more specific type (HTMLAnchorElement is a subtype of HTMLElement)
    3. Through type assertion, the type of aLink becomes more specific, so that you can access the properties or methods unique to the a tag
  • Another grammar is < > grammar, which is not commonly used and can be known:

// If you know the syntax, you will get an error if you use it in jsx of react
const aLink = <HTMLAnchorElement>document.getElementById('link');

Tip: in the browser console, through__ proto__ Gets the type of the DOM element

16. typeof 

  • As we all know, JS provides a typeof operator to obtain the type of data in JS
console.log(typeof 'Hello world'); // ?
  • In fact, TS also provides a typeof operator: the type of variable or attribute can be referenced in the type context (type query)
  • Usage scenario: obtain the type of the value according to the value of the existing variable to simplify the type writing
let p = { x: 1, y: 2 };
function formatPoint(point: { x: number; y: number }) {}
formatPoint(p);

function formatPoint(point: typeof p) {}
  • Explanation:
    1. Use the , typeof , operator to obtain the type of variable p, and the result is the same as the first (type of object literal form)
    2. The environment in which typeof appears in the type annotation (after the colon of the parameter name) is in the type context (different from JS code)
    3. Note: typeof can only be used to query the type of variable or attribute, and cannot query other types (such as the type of function call)

Tags: Javascript Front-end TypeScript

Posted by UQ13A on Sun, 01 May 2022 22:59:20 +0300