Typescript basic types of projects and Precautions Introduction

Typescript files from the source to the implementation of

Executor step Explanation
TSC 1. TypeScript Source -> TypeScript AST TSC will ts files into TS AST (abstract syntax tree)
TSC 2. AST is checked by typechecker TSC's type checker for AST type checking
TSC 3. TypeScript AST -> Javascript Source TSC into the TS AST JS source code (which may be ES3 / 5/6)
JS (browser /Node.js) 4. Javascript Source -> Javascript AST JS JS source code into runtime JS AST
JS (browser /Node.js) 5. Javascript AST -> bytecode JS JS AST will run into byte code, ready to run
JS (browser /Node.js) 6. Bytecode is evaluated by runtime Js JS running bytecode runtime

TSC is 1-3 wherein the processing step, the processing step 4-6 runtime JS, browser may also be Node.js.

From the above steps may know, TSC type checking is done before the TS AST into JS source, that is to say when TS AST converted from JS source, type checking is not done. Check the type for TS AST, that the second step.

TS also means that the type of system, strongly typed mechanisms only useful for type checking, no effect on the output of JS, JS increase does not pollute the type of source file.

About tsconfig.json

-Init can create tsconfig.json file by tsc, as follows:

{
  "compilerOptions": {
    "target": "es2015",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["es2015"],                             /* Specify library files to be included in the compilation. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "dist",                        /* Redirect output structure to the directory. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  }
}

Here mainly to see several common configuration:

Configuration Properties description
include TSC told where to find the file ts
lib Tell TSC current runtime API already exists, usually including: bind ES5, the new array method, ES6 of new methods
module TSC will tell ts files into a standard module that js file, usually cmj, cmd, es6 etc.
outDir File tells TSC converts into which directory
strict TSC tell whether strict type checking
target TSC convert ts to tell which version of js, usually ES3, ES5, ES6, etc.
noImplicitAny Whether to allow the presence of undefined type, i.e. implicit type. TSC will not guess yourself type
alwaysStrict TSC will bring the use strict statement in each js file output in

About tslint

-Init can create a default tslint.json files tslint, as follows:

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}

{}Types of

When a variable type is set to {}, which means the value of this variable may be any value other than the null and undefined.

let a:{} = 1;
let b:{} = Symbol('b');
let c:{} = null; // Type 'null' is not assignable to type '{}'.
let d:{} = undefined; // Type 'undefined' is not assignable to type '{}'.

object type

When a variable to the object type, meaning that the value of this variable can be any value other than strings, numbers, Symbol, null, undefined, a Boolean value.

let a:object = new Date();
let b:object = function(){};
let c:object = [];
let d:object = new RegExp('');
let e:object = true; // Type 'true' is not assignable to type 'object'.
let f:object = Symbol(); // Type 'symbol' is not assignable to type 'object'.
let g:object = 1; // Type '1' is not assignable to type 'object'.
let h:object = '1'; // Type '"1"' is not assignable to type 'object'.

Object Types

same type.

Value {} object Object
{} Yes Yes Yes
[‘a’] Yes Yes Yes
function(){} Yes Yes Yes
new String(‘a’) Yes Yes Yes
‘a’ Yes No Yes
1 Yes No Yes
Symbol() Yes No Yes
true Yes No Yes
null No No No
undefined No No No

[]Types of

When a variable is declared as [] type, represents the value of the variable must be an empty array. If implicit declaration is [], it indicates the type of element is any, i.e., any type of value. Such as:

let a:[] = [];
a = [1]; // Type '[number]' is not assignable to type '[]'.
let b = []; // 隐式声明b为数组,元素类型是any类型
b.push(1);
b.push(null);

Tuples type

This type is a sub-array type, inherited from the array type. Tuples type array must explicitly declare the type of elements, and the array length immutable. Such as:

// 声明定长的数组
let arr: [string,number,boolean] = ['a',2,true];

// 二维数组的声明
// 分步解释:
// let data: number[] 表示声明一个元素为数字的数组
// let data: [][] 表示声明一个元素为空数组的数组
// let data: [number, number][] 表示声明一个元素为两个元素的tuples类型的数组,且tuples的两个元素必须都为number类型
// let data: [number, number?][] 表示数组的第二个元素可选
let data: [number, number?][] = [[1,2],[3],[4,5]];

// 声明不定长数组,且指定第一个元素的类型,其他元素类型任意
let data1: [string,...any[]] = ['11','s',32];

Enumerated type

Enumerated types mainly deal with two types of transactions: the definition of digital mapping or string to string to string mappings. TS automatically mapped to each member of the enumerated type a number, starting from 0 by default, but is also explicitly defined number, the start position to decide, such as:

// 默认从0开始
enum lang {Chinese, English, Russian}; 
let a = lang.Chinese;
console.log(a, lang.English, lang.Russian); // 0, 1, 2
// 定义从3开始
enum lang {Chinese=3, English, Russian}; 
let a = lang.Chinese;
console.log(a, lang.English, lang.Russian); // 3, 4, 5
// 自定义或者自动赋值
enum lang {Chinese=3, English=6, Russian}; 
let a = lang.Chinese;
console.log(a, lang.English, lang.Russian); // 3, 6, 7

See form the enumerated type is converted to TS, such as:

var lang;
(function (lang) {
    lang[lang["Chinese"] = 3] = "Chinese";
    lang[lang["English"] = 9] = "English";
    lang[lang["Russian"] = 10] = "Russian";
})(lang || (lang = {}));
;

We can be accessed via the digital-to-string, access to digital by a string, such as:

console.log(lang['English'], lang[lang.English]); // 9 English

readonly modifier

An attribute of an object is declared readonly

let a: {a:string, readonly b:number} = {a:'2', b:3};
a.b = 4; // Cannot assign to 'b' because it is a read-only property.

Declare an array as read-only

let as: readonly number[] = [1,2,3];
as.push(2); // Property 'push' does not exist on type 'readonly number[]'.
as.concat(3); // concat函数不会对原数组修改,而是返回新的数组,所以此处合法。

// 还可以这样声明
let arr: ReadonlyArray<string> = ['2'];
arr.push('3'); // Property 'push' does not exist on type 'readonly string[]'.
// 或者
let arr: Readonly<string[]> = ['22'];

Read-only attribute class declaration. Read-only attribute class can be assigned at the time of declaration, constructor or assignment elsewhere are not allowed to assign. Such as:

class Foo{
    readonly bar = 1;
    readonly baz:string;
    constructor(){
        this.baz = 'hello';
    }
    setBaz(value:string){
        this.baz = value; // Cannot assign to 'baz' because it is a read-only property.
    }
}
console.log(new Foo().baz);

Type of combination

Sometimes the value of a variable may be required to take a certain type of other types, for the type of case can be set for this variable and set these types, such as:

let prop: string|number = 3;
prop = '3'; // 可以被赋值,因为prop可以为string和number类型中的一个

// 数组里可以是字符串也可以是数字
type StringOrNumber = string|number;
let a: StringOrNumber[] = []; // 或者直接这样:let a: (string|number)[] = [];
a.push(1);
a.push('a');
a.push(true); // 类型错误,不可以有布尔类型

type Cat = {name:string, purrs:boolean};
type Dog = {name:string, barks:boolean, wags:boolean}
type CatOrDogOrBoth = Cat|Dog;
let cat: CatOrDogOrBoth = {name: 'John', purrs: true};
// 类型错误 {name: 'John', barks: false} 不属于Cat和Dog中的任何一个类型
let cat2: CatOrDogOrBoth = {name: 'John', barks: false}; 
// 类型错误,同上
let cat3: CatOrDogOrBoth = {name: 'John', wags: false};
// 类型错误, 同上
let cat4: CatOrDogOrBoth = {barks: true, wags: false};
// 属于Cat类型,因为没有barks属性,即不是Dog类型,且完全拥有Cat类型定义的所有属性
let cat5: CatOrDogOrBoth = {name: 'John', purrs: true, wags: false};
// 既是Cat类型也是Dog类型
let cat6: CatOrDogOrBoth = {name: 'John', barks: false, wags: false, purrs:false}

Guess you like

Origin www.cnblogs.com/ywxgod/p/11730023.html