以实例的形式展示
1.ts定义函数
//1 普通用法 function run(): string { return 'run'; } // function run1(): string { // return 111; //报错 // } //2 匿名函数方式 let fun1 = function (): number { return 123; } console.log(fun1());
2.函数传参
(1)传递等量参数
function getInfo(uname: string, age: number): string { return `${uname}---${age}`; } console.log(getInfo('lisi', 12));
(2)可选参数 (使用?)
// 可选参数 function getInfo(uname: string, age?: number): string { if (age) { return `${uname}---${age}`; } else { return `${uname}---年龄保密` } } console.log(getInfo('lisi', 12)); console.log(getInfo('lisi'));
(3)默认参数
function getInfo(uname: string, age: number = 20): string { if (age) { return `${uname}---${age}`; } else { return `${uname}---年龄保密` } } console.log(getInfo('lisi'));
console.log(getInfo('lisi',30));
(4)剩余参数
①普通写法
function sum(a: number, b: number, c: number, d: number): number { return a + b + c + d; } console.log(sum(1, 2, 3, 4));
②三点运算符
function sum1(...res: number[]): number { return res.reduce((p, e, i, a) => { return p + e; }, 0) } console.log(sum1(1, 2, 3, 4, 5));
(5)函数重载
js的函数重载,是通过为同一函数提供多个函数类型定义来实现多种功能的目的
function getInfo(nam: string): string; function getInfo(age: number): number; function getInfo(str: any): any { if (typeof str === 'string') { return `我叫:` + str; } else { return `年龄:` + str; } }; console.log(getInfo('张三')); console.log(getInfo(25)); console.log(getInfo(错误)); //错误