function run (name: string, age: number): string {
return `${name}---${age}`
}
run('bob', 14)
let run = function (num: number): number {
return num
}
run(18)
let run = (name: string, age: number): string => {
return `my name is ${name} , i am ${age}`
}
run('john', 30) // my name is john , i am 30
let run = function (): void {
console.log(123)
}
run()
function run (name: string, age?: number): string {
if (age) {
return `${name}---${age}`
} else {
return `${name}---年龄保密`
}
}
run('lucy')
function run (name: string, age: number = 18): string {
return `${name}---${age}`
}
run('tom')
function run1 ([first, second]: [number, number]) {
return first + second
}
function run2 ({first, second}: {first: number, second: number}) {
return first + second
}
function run3 ({first, second}: any) {
return first + second
}
function run (a: number, b: number, ...args: number[]): number {
return a + b + args.reduce((v1, v2) => {
return v1 + v2
})
}
run(1, 2, 3, 4, 5) // 第一二个数指向 a b ,剩余指向 args
重载指的是两个或两个以上的同名函数,但它们的参数不一样,这时会出现重载情况
function run1 (name: string): string;
function run1 (age: number): number;
function run1 (str: any): any {
if (typeof str === 'string') {
return `my name ${str}`
} else {
return `i am ${str}`
}
}
run1('bob') // my name bob
run1(18) // i am 18
function run2 (name: string): string;
function run2 (name: string, age: number): number;
function run2 (name: any, age?: any): any {
if (age) {
return `my name ${name} , i am ${age}`
} else {
return `my name ${name}`
}
}
run2('lucy') // my name lucy
run2('lucy', 18) // my name lucy , i am 18