TypeScript参数的灵活性:可选与默认参数的实践

TypeScript参数的灵活性:可选与默认参数的实践

在JavaScript中,函数参数默认都是可选的,这意味着你可以调用函数时不传递任何参数。例如:

function test(x, y) {
    console.log("x: " + x);
    console.log("y: " + y);
}
test();
test(1);

输出结果为:

x: undefined  
y: undefined  
x: 1  
y: undefined  

然而,在TypeScript中,默认情况下所有参数都是必需的。如果我们用TypeScript重写上面的代码,将会得到编译错误:

function test(x: number, y: number): void {
    console.log("x: " + x);
    console.log("y: " + y);
}
test();
test(1);

编译错误为:

ts-no-optional.ts(6,1): error TS2554: Expected 2 arguments, but got 0.
ts-no-optional.ts(7,1): error TS2554: Expected 2 arguments, but got 1.

在TypeScript中声明可选参数

在TypeScript中,我们可以通过在参数后面添加?来声明一个参数是可选的。这与我们在接口中描述对象属性时使用可选属性的方式类似:

function test(x: number, y?: number): void {
    console.log("x: " + x);
    console.log("y: " + y);
}
test(1);
test(1, 2);

输出结果为:

x: 1  
y: undefined  
x: 1  
y: 2  

需要注意的是,任何可选参数都必须跟在必需参数之后。例如,下面的代码将会导致编译错误:

function test(y?: number, x: number): void {
    console.log("x: " + x);
    console.log("y: " + y);
}

编译错误为:

ts-optional-param-wrong-ordering.ts(1,27): error TS1016: A required parameter cannot follow an optional parameter.

默认参数

TypeScript同样支持ES6的默认参数特性,这甚至适用于ES6之前的版本。在TypeScript中,你可以为函数参数指定默认值:

function test(x: number, y: number = 3): void {
    console.log(`x= ${x}, y=${y}`);
}
test(2);
test(2, 5);

输出结果为:

x= 2, y=3  
x= 2, y=5  

如果你在编译TypeScript时使用了--target es6标志,生成的JavaScript代码将会使用ES6的默认参数语法。如果没有使用该标志,编译器将会生成一个检查undefined并赋值的逻辑。

函数类型中的可选/默认参数

可选参数也可以包含在函数类型定义中。例如:

let f: (x: number, y?: number) => void;
f = function(x: number, y?: number): void {
    console.log(`x= ${x}, y=${y}`);
}
f(3);

输出结果为:

x= 3, y=undefined  

但是,不能在函数类型定义中包含默认参数。例如:

let f: (x: number, y: number = 2) => void;

编译错误为:

default-params-function-type.ts(1,20): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.

如果函数实现具有默认参数,它可以被赋值给一个具有相应参数的可选的函数类型。例如:

let f: (x: number, y?: number) => void;
f = function(x: number, y: number = 2): void {
    console.log(`x= ${x}, y=${y}`);
}
f(3);

输出结果为:

x= 3, y=2  

示例项目

本博客使用了以下依赖和技术:

  • TypeScript 3.0.3

通过这个示例,我们可以看到TypeScript在函数参数方面的灵活性,以及如何利用可选参数和默认参数来编写更加健壮和灵活的代码。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

t0_54coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值