如何从类自身的方法中推断出类泛型
class Controller<Body extends Record<string,any>> {
public main(body: Body) {
// This should have auto complete too for the body.a
console.log({ body })
}
public getBody(): Body {
return {a:'b'} //error
}
}
// This should not need any generic parameter
const controller = new Controller()
// This should have auto complete
controller.main({a:'b'})
错误是
输入 '{ a: 字符串; }' 不可分配给类型“Body”。 '{ a: 字符串; }' 可分配给类型“Body”的约束,但“Body”可以使用约束“Record
”的不同子类型进行实例化。(2322)
我删除了一些代码。最初它使用
zod
对象作为主体。另外这个类应该是抽象的,但我也删除了它以使其更简单。
如果你不需要你的类是通用的,你可以删除通用部分,并使用
ReturnType
实用程序类型,如下所示:
class Controller {
public main(body: ReturnType<Controller["getBody"]>) {
console.log({ body })
}
public getBody() {
return { a: 'b' }
}
}
这将为您提供所需的自动完成功能。
希望有帮助!