Understand the type system and TypeScript basic types

1. What is a program?

Program = data structure + algorithm = data in various formats + data processing logic

2. The data is formatted (type)

  • String, Number, Boolean, Null, Undefined
  • Object, Array, Function, Collection

Three, the program may be wrong

  • Calculation error (perform some mathematical operations on non-numeric data)
  • Call a non-existent method, different types of data have different operation methods or methods, such as: string type data should not directly participate in mathematical operations

4. Dynamically typed language & statically typed language

[1] Dynamically typed language

Languages ​​that do data type checking during the running of the program, such as JavaScript

[2] Statically typed language

Language for data type checking during program compilation, such as: Java

Five, the advantages and disadvantages of statically typed languages

The core of statically typed languages: the type system

[1] Advantages

  • Some potential errors can be found in the program compilation stage (with IDE, editor or even in the coding stage) to avoid errors after the program runs in the production environment
  • Coding standards are conducive to team development and collaboration, but also more conducive to large-scale project development and project reconstruction
  • Cooperate with IDE and editor to provide more powerful code intelligent prompt/check
  • Code is document

[2] Disadvantages

  • trouble
  • Lack of flexibility

Six, the advantages and disadvantages of dynamically typed languages

Contrary to the advantages and disadvantages of dynamically typed languages

7. What is a type system

The type system consists of two important components

  • Type annotation (definition, annotation)-typing
  • Type checking (checking)-type-checking

8. Type labeling

Type annotation is to add type descriptions to data (variables, functions (parameters, return values)) in the code. After a variable or function (parameter) is annotated, it cannot store or pass in types that do not conform to the annotation type. With annotations, the TypeScript compiler can perform type legal detection on these data according to the annotations. With annotations, various editors, IDEs, etc. can provide intelligent prompts

Nine, type detection

As the name implies, it detects the type of data. Note that here, the focus is on the word type. The type system detects the type, not the specific value (although, sometimes it can also detect the value), such as the value range of a parameter (between 1-100). We cannot rely on the type system to complete this detection. It should It is the specific logic of our business layer, and the type system detects whether its value type is a number!

10. TypeScript Type labeling

In  TypeScript , the basic grammatical format of type annotation is:

数据载体:类型

let name:string = 'dingFY' // name:string
let age:number = 24 // age:number

TypeScript The type label, we can divide it into

  • Basic simple type annotation
  • Advanced in-depth type annotation

Eleven, basic simple type annotation

  • Basic type
  • Empty and undefined types
  • Object type
  • Array type
  • Tuple type
  • Enumerated type
  • No value type
  • Never type
  • Any type
  • Unknown type

12. Basic types

Basic types include: string, number, boolean

let str: string = '字符串';
let n: number = 100;
let isOk: boolean = true;

Thirteen, empty and undefined types

Because in  Null and  Undefined both types have one and only one value in a variable mark  Null and  Undefined type, it means that the variable can not be modified

let a: null;
// ok
a = null;
// error
a = 1;

By default,  null sum  undefined is a subtype of all types. That means you can assign the  null sum  undefined to other types of variables

let a: number;
// ok
a = null;

If a variable is declared, but not assigned, then the value of the variable  undefined, but if it is also not annotated type, the default type is any

// 类型为 `number`,值为 `undefined`
let a: number;
// 类型为 `any`,值为 `undefined`
let a

Because both  null and  undefined are subtypes of other types, there will be some hidden problems by default

let a:number;
a = null;
// ok(实际运行是有问题的)
a.toFixed(1);

Tips: Specify the strictNullChecks configuration  in the tsconfig.json file to  trueeffectively detect  null or  undefinedavoid many common problems

{
    "compilerOptions": {
        "outDir": "./dist",
        "target": "es5",
        "watch": true,
        "strictNullChecks": true
    },
    "include": ["./src/**/*"]
}
let ele = document.querySelector('div');
// 获取元素的方法返回的类型可能会包含 null,所以最好是先进行必要的判断,再进行操作
if (ele) {
    ele.style.display = 'none';
}

14. Object type

[1] Built-in object type

In  JavaScript , there are many built-in objects, such as: Object, Array, Date..., we can mark them through the object's constructor or class

let a: object = {};
// 数组这里标注格式有点不太一样
let arr: Array<number> = [1,2,3];
let d1: Date = new Date();

[2] Custom object type

In another case, in many cases, we may need to customize the structure of the object. This time, we can

  • Literal annotation
  • interface
  • Define class or constructor

1. Literal labeling:

let a: {username: string; age: number} = {
  username: 'zMouse',
  age: 35
};
// ok
a.username;
a.age;
// error
a.gender;

优点 : Convenient and direct

缺点 : Not conducive to reuse and maintenance

2. Interface:

// 这里使用了 interface 关键字
interface Person {
  username: string;
  age: number;
};
let a: Person = {
  username: 'zMouse',
  age: 35
};
// ok
a.username;
a.age;
// error
a.gender;

优点 : High reusability

缺点 : The interface can only be used as a type annotation, not as a concrete value. It is just an abstract structure definition, not an entity, and no concrete function implementation

3. Class and constructor:

class Person {
	constructor(public username: string, public age: number) {
  }
}
// ok
a.username;
a.age;
// error
a.gender;

优点 : The function is relatively powerful, and the corresponding type is also defined when the entity is defined

缺点 : Complicated, for example, you only want to constrain the parameter structure received by a certain function, there is no need to define a class, it will be easier to use the interface

interface AjaxOptions {
    url: string;
    method: string;
}

function ajax(options: AjaxOptions) {}

ajax({
    url: '',
    method: 'get'
});

【3】Extension

Packing object:

Here that the wrapper object is actually  JavaScript in the  String, , Number, and Booleanwe know the  string type and  String type are not the same, the  TypeScript same is true in

let a: string;
a = '1';
// error String有的,string不一定有(对象有的,基础类型不一定有)
a = new String('1');

let b: String;
b = new String('2');
// ok 和上面正好相反
b = '2';

15. Array type

TypeScript The type stored in the array must be the same, so when labeling the array type, the data type stored in the array must be marked at the same time

[1] Use generic annotations

// <number> 表示数组中存储的数据类型
let arr1: Array<number> = [];
// ok
arr1.push(100);
// error
arr1.push('dingFY');

[2] Simple labeling

let arr2: string[] = [];
// ok
arr2.push('dingFY');
// error
arr2.push(1);

 16. Tuple type

Tuples are similar to arrays, but the stored element types do not have to be the same, but you need to pay attention to:

  • The number of initialization data and the corresponding location label type must be consistent
  • The out-of-bounds data must be one of the types in the tuple annotation (the out-of-bounds data can be labeled without the corresponding order-union type)
let data1: [string, number] = ['dingFY', 24];
// ok
data1.push(100);
// ok
data1.push('100');
// error
data1.push(true);

Seventeen, enumerated types

The role of enumeration is the way to organize a collection of related data. Through enumeration, we can assign friendly names to a group of related data.

enum HTTP_CODE {
  OK = 200,
  NOT_FOUND = 404,
  METHOD_NOT_ALLOWED
};
// 200
HTTP_CODE.OK;
// 405
HTTP_CODE.METHOD_NOT_ALLOWED;
// error
HTTP_CODE.OK = 1;

【1】Notes:

  • key cannot be a number
  • The value can be a number, called a number type enumeration, or a string, called a string type enumeration, but it cannot be other values. The default is a number: 0
  • Enumeration values ​​can be omitted, if omitted, then:
    • The first enumeration value defaults to: 0
    • The non-first enumeration value is the previous numeric enumeration value + 1
  • The enumeration value is read-only (constant) and cannot be modified after initialization

[2] String type enumeration

Enumeration type value, can also be string type

enum URLS  {
  USER_REGISETER = '/user/register',
  USER_LOGIN = '/user/login',
  // 如果前一个枚举值类型为字符串,则后续枚举项必须手动赋值
  INDEX = 0
}

Note: If the previous enumeration value type is a string, the subsequent enumeration items must be manually assigned

Tips: Enumeration names can be uppercase or lowercase, all uppercase is recommended (usually use all uppercase naming methods to mark the value as a constant)

18. No value type

Indicates a type without any data, which is usually used to annotate the return value type of a function without a return value. The default annotation type of the function is:void

function fn():void {
  	// 没有 return 或者 return undefined
}

In  strictNullChecks is  false the case of, undefined and  null may be assigned to  void , but when  strictNullChecks is  true the case, only  undefined can be assigned to void

Nineteen, Never type

When a function can never be executed  return , what is returned is that  never , unlike void, it voidis executed  return, but there is no value, never it will not be executed  return, such as throwing an error, causing the function to terminate execution

function fn(): never {
  	throw new Error('error');
}

Twenty, any type

Sometimes, we are not sure what type the value is or do not need to perform type checking on the value, we can mark it as a  any type

let a: any;
  • When a variable is declared unassigned and unmarked, it defaults to the  any type
  • Any type value can be assigned to the  any type
  • any Type can also be assigned to any type
  • any Type has arbitrary attributes and methods

Note: Marking as a  any type also means giving up the type detection of the value and giving up the IDE’s smart prompt

Tip: When the noImplicitAny configuration is  specified in the tsconfig.json file, an   error will be reported truewhen the function parameter has an implicit  anytype

{
    "compilerOptions": {
        "outDir": "./dist",
        "target": "es5",
        "watch": true,
        "strictNullChecks": true,
        "noImplicitAny": true
    },
    "include": ["./src/**/*"]
}

21. Unknown type

unknow, new in version 3.0, belongs to the security version of any, but is different from any:

  • unknow can only be assigned to unknow, any
  • unknow has no attributes and methods

Twenty-two, function type

Functions are very important in JavaScript, and so are TypeScript. Similarly, functions also have their own type annotation format

  • parameter
  • return value
函数名称( 参数1: 类型, 参数2: 类型... ): 返回值类型;
function add(x: number, y: number): number {
  	return x + y;
}

Articles are continuously updated every week. You can search for " Front-end Collection  " on WeChat to  read it for the first time, and reply to [ Video ] [ Book ] to receive 200G video materials and 30 PDF book materials

Guess you like

Origin blog.csdn.net/qq_38128179/article/details/115062723