1. Data types

Ts functions that do not return a value can be represented by void

function Test: void {
    console.log('this is a no return result of funciton')}Copy the code

Void: undefined: null?

In TS, undefined and null can be subtypes of any type, and can be assigned to variables of any type. Void can not be assigned to ordinary variables

Union types There are many types used for variables

const maxHeight: string | number

interface IProps {
    readonly title: string   // Read-only attributesize? : number// This parameter is optional
    [key:string]: any        // Any type
}

const props:IProps {
    title: 'this is title'.size: 20
}
Copy the code

Note: Interfaces can also be used to constrain arrays, but this is not recommended and can be cumbersome, as follows:

interface INumberArray { [index: number]: number <! Use index type to constrain value type -->}const number: INumberArray = [1.2.3]
Copy the code

It is recommended to use type to constrain the Array type. Type INumberArray = Array

Array type:

1> elemType[]
2> Array<elemType>
Copy the code

Type of function

function sum(x: number,y: number = 2,z? : number) :number{
    return x + y
}

// You can also use... Reset to indicate the remaining parameters
function push(array: any[], ... items: any[]) {
    items.forEach(function(item) {
        array.push(item)
    });
}
Copy the code

Type assertion

A type assertion is not a conversion, it doesn’t really affect the type of a variable

(window as any).foo = 1
Copy the code

3. Double assertion

Idea: Any type can be asserted to any. Any can be asserted to any type

interface Cat {
    run(): void
}

interface Fish {
    swim(): void
}

function testCat(cat: Cat) {
    return (cat as any as Fish)
}
Copy the code

4. A tuple

Idea: Merge objects of different types

let tom: [string, number] = ['Tom'.25]
Copy the code

5. The generic

Idea: Convention input type and output type to be consistent

function sum<T> (x: T, y: T) :T{
    return x + y
}
Copy the code