是否可以为打字稿中的接口函数提供默认参数?
Is it possible to provide default parameter to interface function in typescript?
我将数字 class 扩展如下:
interface Number {
evolution(now: number, before: number): string;
}
Number.prototype.magnitude = function(d=1, suffix="") {
//…
}
而且我喜欢提供默认参数。
但是在没有显式参数的情况下使用它时如下:
label = "÷ " + show.magnitude();
我收到一个错误"The supplied parameters do not match signature"
你需要告诉TypeScript编译器参数是optional:
In JavaScript, every parameter is optional, and users may leave them off as they see fit. When they do, their value is undefined. We can get this functionality in TypeScript by adding a ? to the end of parameters we want to be optional.
下面是一个类似于您要完成的示例:
interface ISum {
(baz?: number, buz?: number): number;
}
let sum: ISum = (baz = 1, buz = 2) => {
return baz + buz;
}
console.log(sum()); //Console: 3
console.log(sum(2)); //Console: 4
console.log(sum(2, 7)); //Console: 9
我将数字 class 扩展如下:
interface Number {
evolution(now: number, before: number): string;
}
Number.prototype.magnitude = function(d=1, suffix="") {
//…
}
而且我喜欢提供默认参数。
但是在没有显式参数的情况下使用它时如下:
label = "÷ " + show.magnitude();
我收到一个错误"The supplied parameters do not match signature"
你需要告诉TypeScript编译器参数是optional:
In JavaScript, every parameter is optional, and users may leave them off as they see fit. When they do, their value is undefined. We can get this functionality in TypeScript by adding a ? to the end of parameters we want to be optional.
下面是一个类似于您要完成的示例:
interface ISum {
(baz?: number, buz?: number): number;
}
let sum: ISum = (baz = 1, buz = 2) => {
return baz + buz;
}
console.log(sum()); //Console: 3
console.log(sum(2)); //Console: 4
console.log(sum(2, 7)); //Console: 9