考虑一下:
interface TArguments {
width?: number,
height?: number
}
interface TSomeFunction {
someFunction ({width, height}: TArguments): void
}
const someObject: TSomeFunction = {
someFunction ({width, height}) {
// do something, no return
}
}
两个参数都是可选的,这意味着我可以调用这样的函数:
someObject.someFunction() // but it is not passing through
我得到一个错误"应为1个参数,但得到了0";。
我是不是错过了什么?当所有参数都是可选的时,我如何编写接口?
您的接口不应该关心默认值或析构函数,因为它们是实现细节。只需将参数声明为可选参数,就好像它是一个标量:
interface TSomeFunction {
someFunction (size? : TArguments): void
}
然后,实现可以定义两者:
const someObject: TSomeFunction = {
someFunction({ width, height } = {}) {
// do something, no return
}
}
您的错误一定来自其他地方(或者尝试重新启动IDE,这是一个非常令人沮丧的来源:(。你的第二种方法看起来是正确的:
const someFunction = ({width, height}: TArguments = {}) => { ... }
这是一个正在工作的TypeScript游乐场链接
EDIT您还需要指定参数本身,而不仅仅是其键,是可选的:
interface TSomeFunction {
someFunction (arguments?: TArguments): void; // Notice the question mark after the parameter expression
}
// Now you can either add a default value to your function
const someObject: TSomeFunction = {
someFunction ({width, height}: TArguments = {}) {}
}
// Or leave it optional without specifying a default value
const someObject: TSomeFunction = {
someFunction ({width, height}?: TArguments) {} // Notice the question mark
}