test.js
export class MyClass {
constructor () {
this.init(...arguments);
}
init(arg, opts) {
console.log(arg, opts);
}
}
以上是完全有效的JavaScript ES6代码。在TypeScript中,您需要定义参数类型:
test.ts
export class MyClass {
constructor () {
this.init(...arguments); // this no worky
}
init(arg: string, opts: Object) {
console.log(arg, opts);
}
}
但打字本版本与this.init(...arguments);
有问题。它抱怨(local var) arguments: IArguments A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
。
如何将“所有参数,无论是什么”传递到子函数,同时避免丑陋的apply(this, args)
构造?
我知道我可以明确地命名所有参数,考虑到这里有2个参数,但让我们假设在我的实际应用程序中,constructor()
和init()
都必须能够接受大量的参数。即使所有参数都已知,在类型记录中、在每个级联子函数调用级别中重复所有参数及其类型也是繁琐和冗长的,因为您已经知道它们只会由子函数init()
传递和处理。
有人建议这个在类型记录函数中扩展数组:错误TS2556已经回答了这个问题。所以我试了一下:
test2.ts
export class MyClass {
constructor (...args: any[]) {
this.init(...args); // STILL throws the TS2556 error
}
init(arg: string, opts: Object) {
console.log(arg, opts);
}
}
它仍然抛出TS2556错误。
发布于 2022-02-12 18:07:55
问题是,TypeScript没有足够的信息来确定类型的正确性:arguments
没有正确地键入,而...args: any[]
显式地表示“一个包含一定数量的任何东西的数组”。您必须自己添加这些信息,并且可以使用内置的Parameters
助手来完成此操作:
constructor (...args: Parameters<MyClass["init"]>) {
this.init(...args);
}
https://stackoverflow.com/questions/71093628
复制相似问题