TS Learning 04-Function

function

function type

define a type for the function

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

ts can automatically infer the return type from the return statement, so we usually omit it.

Expression functions (anonymous functions)

const add:(x:number, y:number) => number = function(x,y) {
    
    return x + y}

Contains parameter types and return value types.

If the function does not return any value, the return value type must be specified voidand cannot be left blank.

inferred type

If the anonymous function parameter in the above expression function does not specify a type, the typeScript compiler will automatically recognize the type

This is called "categorization by context" and is a type of type inference.

Optional parameters and default parameters

Every function parameter in ts is required. The compiler checks that the user has not entered a value for each parameter.

function add (a:string,b:number){
    
    }
add('1')//error
add('1',1,1)//error
add('1',1)

Implement optional parameter functions

Beside the parameter use

Optional parameters must come after required parameters

function add (a:string, b?:number) {
    
    }
provide a default value
function add (a: string, b: number = 1) {
    
    }
add('1')
add('1',1)
add('1',1,1)//error

Parameters with default values ​​do not need to be placed after required parameters

remaining parameters

function add (a:string, ...restArgs:any[])

There can be none, or any number.

this parameter

I don't understand, I don't see it at first glance

overload

not at first glance

Guess you like

Origin blog.csdn.net/weixin_46211267/article/details/132186229