Advanced TypeScript

Type assertion

Assertion type (Type Assertion) a developer manually specify a value of the type:
<type> value or value as type

You must use values ​​as type tsx syntax (React syntax of jsx ts version) in.

For example: a joint type variable is specified as a more specific type (but not designated as type union type does not exist):

// 使用联合类型时,必须使用这些类型共有的属性才行,但使用类型断言使其确定为某一种类型,就没有了此限制。
function getLength(something: string | number): number {
    if ((<string>something).length) {    //<string>something类型断言为字符串,就可以使用字符串独有的属性方法。
        return (<string>something).length;
    } else {
        return something.toString().length;
    }
}

Type inference:

If you do not explicitly specify the type, TS will rule in accordance with the type inference (Type Inference) infer a type:

let myFavoriteNumber = 'seven';      //无错
myFavoriteNumber = 7;                //Type 'number' is not assignable to type 'string'.

Their type is not specified, the TS will automatically inferred any type, if specified, such as 'seven', TS automatically inferred type string.

Note: the declaration does not distinguish between the assignment, the assignment statement will not set any value type: any

Type inference (Type Inference) refers to an automatic programming language can be derived the value of the data type of the compile-time capacity, which is characteristic of some strongly statically typed language.

Optional parameters

Like optional attributes interface with? Indicate optional parameters.

Optional parameters must be connected behind the required parameters, there can not be the parameter selection parameters.

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

Union type

Union type using | to separate each type of representation can be assigned to one of them.

let myFavoriteNumber: string | number;  //允许 myFavoriteNumber 的类型是 string 或者 number,但是不能是其他类型。
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;           // 无错

Note: When a union type of TS uncertain variables in the end is what type of time (such as when a defined method), we can only access the properties or methods to all types of this type of union in common:

function getLength(something: string | number): number {
    return something.length;    //   Property 'length' does not exist on type 'string | number'.
    //  length 不是 string 和 number 的共有属性,所以会报错。
    //  但访问 string 和 number 的共有属性不会报错,如:return something.toString();

When the union type of a variable is assigned at the time, the rules will be inferred from the type inference of a type, then access to the type of property does not complain.

Type of object: Interface

In TS, using the type of interface (Interfaces) to define the object.

Interface Interfaces are abstract behavior, and how to act by specific classes that to achieve (implement).

TS The interface is a very flexible concept that can be used in addition to behavior on the part of the abstract class outside, is also often used to "shape (Shape) object" description.
As: define an interface Person, and then defines a variable tan, which is of type Person. Thus, the constraints and tan shape Interface Person must be consistent (more or fewer properties are being given):

interface Person {
    name: string;
    age: number;
}
let tan: Person = {
    name: 'tan',
    age: 22
};

Optional attributes (still not allowed to add interface attributes)

When an interface that some properties are not needed, set optional attributes, you can do it:

interface Person {
    name: string;
    age?: number;       //设为可选属性   
}
let tan: Person = {
    name: 'tan'
};

Any property

If any attribute, to determine the properties and type of optional attributes of any type must be a subset of properties.

interface Person {
    name: string;
    [propName: string]: any;        //定义了任意属性,取 string 类型,属性值取any类型。
}
let tom: Person = {
    name: 'tan',
    gender: 'male'
};

Read-only attribute

If the object in some fields require only created when they were assigned, using the read-only attribute definitions readonly (read-only constraint is present in the first assignment to the object when, not for the first time to the read-only attribute assignment when )

interface Person {
    readonly id: number;
    name: string;
    age?: number;
    [propName: string]: any;
}
let tom: Person = {
    id: 89757,
    name: 'Tom',
    gender: 'male'
};
tom.id = 9527;      //  Cannot assign to 'id' because it is a constant or a read-only property.

Interface inheritance

Interface inheritance means that the interface can extend themselves through other interfaces.

Typescript allows the interface to inherit more than one interface.

Inherited keyword extends.

Single interface inheritance syntax:

Child_interface_name extends super_interface_name

Multiple interface inheritance syntax:

Child_interface_name extends super_interface1_name, super_interface2_name,,super_interfaceN_name

Inherited each interface using a comma separated.

Type array

TS, the array defined in various ways.

** Method One: ** Use "square brackets type +" to represent the array (type can be any):

let fibonacci: number[] = [1, 1, 2, 3, 5];  //数组的值只能是number类型
let list: any[] = ['Xcat Liu', 25];  //数组的值可以是任意类型

Item in the array does not allow other types of methods and parameters can not be other array types, such as: push ().

** Method Two: ** array of generics:

let fibonacci: Array<number> = [1, 1, 2, 3, 5];

Method three : The array interface description:

interface NumberArray {
    [index: number]: number;   //只要 index 的类型是 number,那么值的类型必须是 number。
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];

Method four : array-:

function sum() {
    let args: number[] = arguments;//错误,arguments缺少属性push
}

// index.ts(2,7): error TS2322: Type 'IArguments' is not assignable to type 'number[]'.
//   Property 'push' is missing in type 'IArguments'.

In fact the common array of classes has its own interface definition, such as IArguments, NodeList, HTMLCollection such as:

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

Type function

In JS, there are two common ways defined function - a function declaration (Function Declaration) expression and function (Function Expression).

Function declaration:

function sum(x: number, y: number): number {
    return x + y;
}

Too many parameters or parameter being given inadequate

Function expression:

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

Definition of the type of TS => used to represent the function definition, the left input type is required parentheses, brackets on the right is the output type.
In ES6, a => is a function of the arrows.

The interface function is defined by

Interface description object, an array, are equally applicable to the function:

interface SearchFunc {     //定义一个接口
    (source: string, subString: string): boolean;
}
let mySearch: SearchFunc;   //定义mySearch类型为SearchFunc
mySearch = function(source: string, subString: string) {
    return source.search(subString) !== -1;
}
// 相当于接口的属性是函数的参数,返回值是接口的属性值。

Parameter Default

In ES6 allowed to add default values ​​of parameters of the function, the TS will add the default values ​​for the parameter identification optional parameters, optional parameters and therefore may not be connected after the required parameters.

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

The remaining parameters

Also in ES6 can be used ... rest way to obtain all of the remaining functions of the parameters:

function push(array: any[], ...items: any[]) { 
    items.forEach(function(item) {  ////将items的每一项push进array
        array.push(item);
    });
}
let a = [];
push(a, 1, 2, 3);  // a是一个数组,...items就是剩余的参数1,2,3

Function overloading

Function overloading allows a function that takes a different number or type of parameters, and make different processing.

TS will give priority to start match-defined functions from the front, so if you have more than one function defined containment relationship, you need to give priority to precise definition EDITORIAL. Such as:

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

declare function test(para: User | number, flag?: boolean): number;

In this test function, our intention is probably when an incoming parameter para is User, does not pass the flag, when an incoming para a number, incoming flag. TypeScript did not know, when you pass para to User, flag also allows you to pass:

const user = {
  name: 'Jack',
  age: 666
}

// 没有报错,但是与想法违背
const res = test(user, false);

Use function overloading can help us achieve:

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

declare function test(para: User): number;
declare function test(para: number, flag: boolean): number;

const user = {
  name: 'Jack',
  age: 666
};

// bingo
// Error: 参数不匹配
const res = test(user, false);

declare only play the role of prompt, does not participate in any logic to achieve, if the call declare a method ever achieved, then no js error.

Published 32 original articles · won praise 112 · views 60000 +

Guess you like

Origin blog.csdn.net/liuyifeng0000/article/details/104439963