TypeScript canonically and systematically learn

TypeScript canonically and systematically learn

TypeScript canonically and systematically learn

The author is a new one. This study summary is also my first summary after learning TypeScript. I think the summary is the crystallization of learning. In the future, I will often publish some of my study summaries including some personal study insights on Nuggets and other websites.

1 Introduction

TypeScript is a superset of JavaScript. TypeScript is based on JavaScript. The top layer is the TypeScript type system.

First talk about JavaScript, JavaScript already have a foundation in their own language, such as string, number, object, undefinedand so on. But because it is a dynamic language, without compiling, you cannot compile after the code is written, so as to complete type checking and syntax checking.

Moving on to TypeScript, TypeScript plays the role mentioned above. So, after summing up, we know that TypeScript is a runtime that includes JavaSctip, and it also expands a superset of JavaScript at compile time that JavaScript does not have.

Therefore, it can be extended to know that TypeScript can use any JavaScript code.

2. TypeScript type system

Type system-basic types

Type annotation

TypeScript needs to complete type checking at compile time. Type annotations are usually used to help complete type checking, and type annotations are generally as follows

let title: string = ' ';
let n: number = 100;
let isOk: boolean = true;
 

Type annotations for basic types

TypeScript needs to complete type checking at compile time. Therefore, many variables need to be declared in TypeScript syntax format when declaring them, instead of being not rigorously declared by JavaScript.

The syntax of type annotation islet : ;

example:

let helloWorld = "Hello World"; 			// JavaScript 
//let helloWorld: string = "Hello World";  // TypeScript 

// string,number,boolean 
let title: string = ' ';
let n: number = 100;
let isOk: boolean = true;
 

Type inference

If you do not use type annotations, you can initialize the variable when you declare it so that it is bound to the default type, so that type annotations can be omitted. The same is true for function parameters and return values.

example

let helloWorld = "Hello World"; 			//helloWorld string .
//function fn(x: number, y: number): number
function fn(x=1, y=1) {
    return x + y;
}
console.log(fn(1,1))
console.log(fn('1',1))//"1" number | undefined ts(2345)
 

Type system-array tuple enumeration

Array type annotation

Array type annotation syntax let : [];that is defined as an established array of type can not be added to an array of other types of elements.

There is also a syntax that uses a generic format, ie let :Array< >;.

example

let arr1: string[] = [];
arr1.push(' ');// 
//arr1.push(1);// 
// 1 string ts(2345)

let arr2: Array<number> = [];
arr2.push(100);// 
arr2.push('100');// 
//arr2.push(' ');//                  
// " " number ts(2345)
 

Type annotations for tuples

Tuples are similar to arrays, but the stored element types do not have to be the same.

But there are two points to follow.

1. It must be initialized first, and the type and order of the initialized value must be consistent with the variable type and order of the tuple.

2. After initializing the tuple, you can continue to add it beyond the bounds, but the added elements must be of several types defined in the tuple.

Note: Not open strictNullChecks: truewill use undefinedto initialize

The annotation syntax for tuple types is let : [ , ,...].

example

let data1: [string, number] = [' ', 100];
data1.push(100);// 
data1.push('100');// 
data1.push(true);// 

let data2: [string, number] = [' ', 100];
data2.push(10);
 

Enumeration type annotation

TypeScript's enumerated types are implemented through the enum keyword.

The type annotation syntax of enumeration is as follows enum { key1=value, key2=value2 }.

note:

1. In the comment syntax, a comma (,) is used to separate key=value.

2. The previous one is an initialized number, if the next enumeration variable does not set a value, the enumeration variable is based on the previous variable +1

3. If the enumerated variable does not specify a value, the default is 0, 1, 2, 3...

4. The key is not allowed to start with a number.

5. Value can be a number, called a number type enumeration, or a string, called a string type enumeration, but cannot be other values, the default is a number: 0

The fifth point is the easiest to forget, so remember that there are only two types of enumerations.

example:

enum HTTP_CODE {
    OK = 200,// 
    NOT_FOUND = 404// 
};
//HTTP_CODE.OK;//200

enum URLS {
    USER_REGISTER = '/user/register',//
    USER_LOGIN = '/user/login'		//
}
enum SEQ {
    SEQ = 200,// 
    SEQ1 	//201
};
 

Type system-other types

viod type

Usually used in functions, if the return value of the function is undefined or (but when it is executed to return) there is no return value, the type annotation can be declared as : void

Type annotation syntax : void. That means there is no type of data.

example:

// 
function fn(): void {
    
}
fn();
let fnfn :void = undefined;
 

never type

Usually used in functions, when the function is executed, when the return is not executed, the return type of the function is never.

The annotation syntax is: : never

Note: Never is a subtype of other types. (But not the other way around)

example:

let fnfn :void = undefined;
function fn(): never {
    throw new Error('Error');
}
let a: string;
a = fn();		//never string 
fnfn = fn();	//never void 
let b : any;
b = fn();		//never any 
// 
//let b: never;
//let c: any = 1;
//b = c;
 

any type

If the type is really uncertain, you can clearly declare that the variable is of type any.

The syntax of type annotation is :any

note:

1. Any value can be assigned to anytype

2. The anytype can also be assigned to any type

3. The anytype has arbitrary attributes and methods

4. labeled anytype, the type of detection also means giving up the values, while giving up the IDE's IntelliSense

(Tip: Specify noImplicitAnyconfigured true, when the function parameters implied *** *** appearance anybeing given type)

example:

let an: any;

//  any  
an = 1;
an = '1'

//any 
let b: string;
b = an;
let flag: boolean;
flag  = an;

//any 
an.indexOf();

//  noImplicitAny   true
//  any  
function fn(an) {//
   // an any ts(7006)
    an.inde();
}

let a: any;
//VS Code  
a.indexOf(); 
 

unknown type

If the type is really uncertain, but you know that the variable has no methods and variables, you can explicitly declare that the variable is of unknown type.

The syntax of type annotation is :unknown

note:

1. the anysame type, the type can be assigned to any unknowntype of

2. anyDifferent from the type,

unknownType cannot be assigned to any type, only anytype or unknowntype

unknownType does not have any attributes and methods

let a: unknown;
let b: unknown;
let an : any;
// `any` `unknown` 
a = an;
b = a;

//  unknown  
let str :string = "str";
let obj :Object = {}
a = str;
a = obj;

//unknown  
a.indexOf();// 
//  "unknown" ts(2571)
 

Function type

Type annotation syntaxfunction ( 1: 1, 2 2...): {}

let add = function(x: number, y: number): number {
    return x + y;
}

function foreach(data: string[], callback:(k: number, v: string) => void) {
    for (let i:number = 0; i<data.length; i++) {
        callback(i, data[i]);
    }
}

let arr = ['a', 'b', 'c'];
let obj = {}
foreach(arr,function(k,v){})
 

Interface type definition

Note: Interface is a type and cannot be used as a value

JavaScript is a dynamic language that allows multiple design patterns. But after using dynamic programming, under certain circumstances, there are some design patterns that are difficult to automatically provide types.

If these types are static, then TypeScript that provides static programming and supports JavaScript language allows the use of these design patterns. Because the type is determined, TypeScript provides a location to inform the type.

General declaration of interface

An explicit way to describe the type of this interface is through the interfacedeclaration:

interface User {
  name: string;
  id: number;
}
 

Then you can use it

const user: User = {
  name: "Hayes",
  id: 0,
};
 

note:

Declaring the user variable of the User type must be used strictly in accordance with the User object type.

Otherwise, TypeScript will display an error when compiling.

Compatible class use interface type definition

Because JavaScript supports class and object-oriented programming, so does TypeScript-interface declarations can also be used with classes:

interface User {
  name: string;
  id: number;
}

class UserAccount {
  name: string;
  id: number;

  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}

const user: User = new UserAccount("Murphy", 1);
 

Optional attributes, read-only attributes, arbitrary attributes

Optional attributes, read-only attributes, and arbitrary attributes are used in the interface type.

The syntax for optional attributes is ?:

The syntax for read-only attributes isreadonly :

The syntax for arbitrary attributes is[prop: ] :

We want to add arbitrary attributes to an interface, which can be achieved through index types

note:

1. The index type is generally a string or a number.

When defining as a string, you can use numbers. Such as p4[1] = 1;

When it is defined as a number, a character string cannot be used. Such as p4['1'] = 1;//Compile error

2. If two arbitrary attributes are used at the same time,

For example, prop1:string number and [prop2:number]:number are fine, because the attribute types are the same.

But the second one defined as [prop2:number]:Date will report an error. Because the attribute types are different.

The attribute type needs to meet the subtype of the index type as a number and so the type is a string.

//  
interface Point3 {
    x: number;
    readonly y: number;
    color?: string;
}

let p3: Point3 = {
    x: 1,
    y: 1,
};
p3.x;
p3.x = 10;
p3.y
//p3.color = 'green';

//
interface Point4 {
    x: number;
    y: number;
    [prop: string]: number;
}

let p4: Point4 = {
    x: 1,
    y: 1,
    z: 1
}
p4.t = 10;
p4[1] = 1;
 

The following content will be organized next time:

Type in-depth-Union Type-Intersection Type-Literal Type-Type Alias-Type Deduction-Type Assertion

Type in-depth-type operators

Type in-depth-type protection

The article quoted some knowledge from TypeScript's official website . And introduced the learning results of the knowledge points of the latest free learning class of TypeScript in the class.