TypeScript 入门学习(三):TypeScript 函数定义
TypeScript 函数定义
函数定义
// 函数声明法
function fun(): string { return 'xxx';}
// 匿名函数声明法
var fun = function(): string { return 'xxx';}
函数传参
// 传入参数
function foo(name: string, age: number): string {
return `${name}---${age}`;
}
console.log(getInfo('star', 23)); // star---23
可选参数
function foo(bar: number, bas?: string): void {
if (bas) {
console.log(`${bar}---${bas}`);
} else {
console.log(bar);
}
}
foo(123); // 123
foo(123, 'hello'); // 123---hello
注意: 可选参数必须放在必选参数的后面。
// 错误写法
function foo(bar: number, bas?: string, co: string): void {
// ...
}
默认参数
当调用者没有提供该参数时,你可以提供一个默认值(在参数声明后使用 = someValue )。
function foo(bar: number, bas: string = 'hello'): void {
console.log(bar, bas);
}
foo(123); // 123 hello
foo(123, 'world'); // 123 world
Rest 参数
function foo(bar: string, ...arg: number[]): void {
console.log(bar);
for (const e of arg) {
console.log(e);
}
}
foo('hello', 1, 3, 4, 5); // hello 1 3 4 5
注意: Rest 参数必须放在必选参数后面,并且可选参数和 Rest 参数是兼容的。
函数重载
TypeScript 中的重载是通过同一个函数提供多个函数类型定义来实现多种功能的目的。
function foo(name: string): void;
function foo(name: string, age: number): void;
function foo(name: string, age?: number): void {
if (age) {
console.log(`${name}---${age}`);
} else {
console.log(name);
}
}
foo('star');foo('star', 23);
最后一个函数头是在函数体内实际处于活动状态但不可用于外部。TypeScript 中的函数重载没有任何运行时开销。它只允许你记录希望调用函数的方式,并且编译器会检查其余代码。
还没有评论,来说两句吧...