Learning about TypeScript (1) — Data types

In TS, the function is also a little bit different than in ES. We can specify the type of the parameter or the return type of the function. Now let’s look at the functions in TS.

Definition of a function

function Fn() :string { // Define a function that returns a string
    const str:string = '22222'
    return str
}
function Fn1(name:string, age:number) :string { // Constrain the parameter type
    return name + age
}
Fn1('mimi'.6) / / is not an error
Fn1(44.6) // The compiler reported an error
Fn1('wumi') / / an error

// This parameter is optional
function Fn2(name:string, age? :number) :string { / / add? The parameter can be transmitted or not transmitted. The optional parameter must be set to the end of the parameter
    return name + age
}
Fn2('xixixi') / / is not an error


// Default parameters
function Fn(name:string, age:number = 2) :string { // Give the parameter a default value, 2 if age is not passed
    return name + age
}
console.log(Fn('Mimi.3)) / / = > Mimi. 3
console.log(Fn('Mimi)) //= "Mimi 2

// Remaining parameters
function sum(. result:number[]) :number { / /... For the remaining element operator, all parameters passed in are put into the Result array
    return result.reduce((x, y) = > x + y)
}
console.log(sum(1.2.3.4.5))
Copy the code

Function overloading

TS function overloading, by providing multiple function type definitions for the same function to achieve the purpose of multiple functions

// Overloading different parameter types
function User(name:string) :string;
function User(age:number) :number;
function User(str:any) :any{
    if(typeof str === 'string') {return 'I am the name: + str
    }else {
        return 'I am the age: + str
    }
}

User('wumi') / / = > I'm name: wumi
User(true)  //=> error, no Boolean overload

// Overload with different number of parameters
function User1(name:string) :string
function User1(name:string, age:number) :string
function User1(name:any, age? :any) :any{
    if(age){
        return'I am' +name+ ',age:' + age
    }else {
        return "I am" + name
    }
}
console.log(User1('ngawang'.2))  // I am awang, age:2
console.log(User1('ngawang'))    // I am Awang
Copy the code