Typescript technical point summary

Typescript technical point summary

1, primitive data types

Boolean value boolean

let isDone: boolean = false;
//或者构造函数类型
let createdByNewBoolean: Boolean = new Boolean(1);
//或者通过下面方式返回布尔类型
let createdByBoolean: boolean = Boolean(1);

Numerical number

let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
// ES6 中的二进制表示法
let binaryLiteral: number = 0b1010;
// ES6 中的八进制表示法
let octalLiteral: number = 0o744;
let notANumber: number = NaN;
let infinityNumber: number = Infinity;

String string

let myName: string = 'Tom';
let myAge: number = 25;

// 模板字符串
let sentence: string = `Hello, my name is ${myName}.
I'll be ${myAge + 1} years old next month.`;

Null void

JavaScript is not null (Void) concept in TypeScript, the void can be expressed by the function returns no value

function alertName(): void {
    alert('My name is Tom');
}
//声明一个 void 类型的变量没有什么用,因为你只能将它赋值为 undefined 和 null
let unusable: void = undefined;

null 和 undefined

let u: undefined = undefined;
let n: null = null;

与 void 的区别是,undefined 和 null 是所有类型的子类型。也就是说 undefined 类型的变量,可以赋值给 number 类型的变量

// 这样不会报错
let num: number = undefined;
// 这样也不会报错
let u: undefined;
let num: number = u;
//但这样就报错
let u: void;
let num: number = u;
// index.ts(2,5): error TS2322: Type 'void' is not assignable to type 'number'.

Any arbitrary value

If the variable is declared at the time, the type is not specified, then it will be identified as any type of value

let myFavoriteNumber: any = 'seven';
myFavoriteNumber = 7;
//声明一个变量为任意值之后,对它的任何操作,返回的内容的类型都是任意值。

Union type

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;

Joint type properties and methods

//只能访问共有的属性或方法
function getString(something: string | number): string {
    return something.toString();
}

2, object type

Interface Interfaces

interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25
};
//必须一一对应,少属性报错

Optional attributes

interface Person {
    name: string;
    age?: number;
}

let tom: Person = {
    name: 'Tom'
};

Any property

Once the definition of any attribute, then a determination of the type and optional attributes must be a subset of its type

interface Person {
    name: string;
    age?: number;
    [propName: string]: any;
}

let tom: Person = {
    name: 'Tom',
    gender: 'male'
};
let tom1: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};
//tom1报错,age是任意类型的子集,不为字符串

Read-only attribute readonly

//第一次给对象赋值的时候
interface Person {
    readonly id: number;
    name: string;
    age?: number;
    [propName: string]: any;
}

Array

  • The first
let fibonacci: number[] = [1, 1, 2, 5];
  • The second: Generic Array
let fibonacci: Array<number> = [1, 1, 2, 5];
  • Third: array interface represents
interface NumberArray {
    [index: number]: number;
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];
//NumberArray 表示:只要 index 的类型是 number,那么值的类型必须是 number。
  • Fourth: any
let list: any[] = ['Xcat Liu', 25, { website: 'http://xcatliu.com' }];

Class Array

On the common array of classes has its own interface definition, such as IArguments, NodeList, HTMLCollectionand so on:

function sum() {
    let args: IArguments = arguments;
}

function

Function declarations

function sum(x: number, y: number): number {
    return x + y;
}
//执行时多余定义参数或者小于都不被允许

Function expression

let mySum = function (x: number, y: number): number {
    return x + y;
};
//如果需要我们手动给 mySum 添加类型
let mySum: (x: number, y: number) => number = function (x: number, y: number): number {
    return x + y;
};
//这里的 => 不是es6的 => 

The shape of the interface defined function

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    return source.search(subString) !== -1;
}

Optional parameters

function buildName(firstName: string, lastName?: string) {
    if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        return firstName;
    }
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');

可选参数后面不允许再出现必须参数了
Parameter Default

function buildName(firstName: string, lastName: string = 'Cat') {
    return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');

The remaining parameters

//只能是最后一个参数
function push(array: any[], ...items: any[]) {
    items.forEach(function(item) {
        array.push(item);
    });
}

let a = [];
push(a, 1, 2, 3);

Overload

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

Type assertion

Need not determine the type of access time on one type of property or method, you can use the type of assertion

function getLength(something: string | number): number {
    if ((<string>something).length) {
        return (<string>something).length;
    } else {
        return something.toString().length;
    }
}
//类型断言不是类型转换,断言成一个联合类型中不存在的类型是不允许的

Declaration file

Declaration

declare var jQuery: (selector: string) => any;

jQuery('#foo');

The example above, declare vardid not really define a variable, but the definition of the global variable jQuerytype, only will be used for compile-time checking, will be removed at compile results

Global variable declaration file

  • Usually we will declare statement into a separate file ( jQuery.d.ts), which is manifest file
  • Statement required to file d.tssuffix.

Third Party Notices File

npm install @types/jquery --save-dev

Written declaration file

  • If in npm install @types/xxx --save-devthe installation, do not require

declare the

// src/jQuery.d.ts

declare const jQuery: (selector: string) => any;
//使用
jQuery('#foo');

declare function

// src/jQuery.d.ts

declare function jQuery(selector: string): any;
declare function jQuery(domReadyCallback: () => any): any;
//使用
jQuery('#foo');
jQuery(function() {
    alert('Dom Ready!');
});

declare class
declare class statement can only be used to define the type, can not be used to define the specific implementation , such as defining sayHithe specific implementation of the method will be given

// src/Animal.d.ts

declare class Animal {
    name: string;
    constructor(name: string);
    sayHi(): string;
}
//使用
// src/index.ts

let cat = new Animal('Tom');

declare emun
declare emun statement can only be used to define the type, specific values can not be used to define

// src/Directions.d.ts

declare enum Directions {
    Up,
    Down,
    Left,
    Right
}
//使用
// src/index.ts

let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

declare namespace

// src/jQuery.d.ts

declare namespace jQuery {
    function ajax(url: string, settings?: any): void;
}
//使用
// src/index.ts

jQuery.ajax('/api/get_something');

interface and type

// src/jQuery.d.ts

interface AjaxSettings {
    method?: 'GET' | 'POST'
    data?: any;
}
declare namespace jQuery {
    function ajax(url: string, settings?: AjaxSettings): void;
}
//使用
// src/index.ts

let settings: AjaxSettings = {
    method: 'POST',
    data: {
        name: 'foo'
    }
};
jQuery.ajax('/api/post_something', settings);

Prevent naming conflicts

// src/jQuery.d.ts
//放到namespace下
declare namespace jQuery {
    interface AjaxSettings {
        method?: 'GET' | 'POST'
        data?: any;
    }
    function ajax(url: string, settings?: AjaxSettings): void;
}
//使用
// src/index.ts

let settings: jQuery.AjaxSettings = {
    method: 'POST',
    data: {
        name: 'foo'
    }
};
jQuery.ajax('/api/post_something', settings);

Statement merger

// src/jQuery.d.ts

declare function jQuery(selector: string): any;
declare namespace jQuery {
    function ajax(url: string, settings?: any): void;
}
//使用
// src/index.ts

jQuery('#foo');
jQuery.ajax('/api/get_something');

npm package

  • Judge based package.jsonthere are typesfields, or there is a index.d.tsdeclaration file
  • Try to install it corresponds @types package to know whether the declaration file exists, the install command is npm install @types/foo --save-dev
  • Create a typesdirectory specifically designed to manage your files written statement, the foostatement files into types/foo/index.d.tsthe. This approach requires configuration tsconfig.jsonof pathsand baseUrlfields.
目录结构
/path/to/project
├── src
|  └── index.ts
├── types
|  └── foo
|     └── index.d.ts
└── tsconfig.json

tsconfig.json content

{
    "compilerOptions": {
        "module": "commonjs",
        "baseUrl": "./",
        "paths": {
            "*": ["types/*"]
        }
    }
}

export Exports

// types/foo/index.d.ts

declare const name: string;
declare function getName(): string;
declare class Animal {
    constructor(name: string);
    sayHi(): string;
}
declare enum Directions {
    Up,
    Down,
    Left,
    Right
}
interface Options {
    data: any;
}

export { name, getName, Animal, Directions, Options };
//导入模块
// src/index.ts

import { name, getName, Animal, Directions, Options } from 'foo';

console.log(name);
let myName = getName();
let cat = new Animal('Tom');
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
let options: Options = {
    data: {
        name: 'foo'
    }
};

export default export

// types/foo/index.d.ts

export default Directions;

declare enum Directions {
    Up,
    Down,
    Left,
    Right
}

export =

// 整体导出
module.exports = foo;
// 单个导出
exports.bar = bar;
//导入
// 整体导入
const foo = require('foo');
// 单个导入
const bar = require('foo').bar;

export as namespace UMD library

  • Either through <script>labeling introduced, but also by importimported repository, called the UMDlibrary
// types/foo/index.d.ts

export as namespace foo;
export default foo;

declare function foo(): string;
declare namespace foo {
    const bar: number;
}

Direct extension of global variables

interface String {
    prependHello(): string;
}

'foo'.prependHello();

declare globalIn the npmpackage or UMDextend global variable library

// types/foo/index.d.ts

declare global {
    interface String {
        prependHello(): string;
    }
}

export {};
//使用
// src/index.ts
//注意即使此声明文件不需要导出任何东西,仍然需要导出一个空对象,用来告诉编译器这是一个模块的声明文件,而不是一个全局变量的声明文件。

'bar'.prependHello();

Built-in objects

ECMAScript built-in objects

let b: Boolean = new Boolean(1);
let e: Error = new Error('Error occurred');
let d: Date = new Date();
let r: RegExp = /[a-z]/;

DOM and BOM of built-in objects

let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click', function(e: MouseEvent) {
  // Do something
});

Guess you like

Origin blog.csdn.net/weixin_42204698/article/details/92667795