我正在try 引入一个API,在该API中传递对象,对象的方法将有this
个类型作为对象本身,而不显式地指定对象的类型.
我试过这个:
interface BaseProcessor<T> {
process(this: Readonly<T>): void;
[key: string | symbol]: unknown;
}
function makeProcessor<T extends BaseProcessor<T>>(definition: T) {
// code...
}
export const processor = makeProcessor({
hello: "world!",
// other possible properties of different types...
process() {
console.log(this.hello); // <--- this.hello is of type "unknown"
}
});
我想要实现的是有this.hello
个类型是string
.类似地,添加到对象中的其他属性将在this
上键入它们的值,但稍微更改类型(例如,使它们像提供的示例中一样).
有可能做到吗?任何帮助或建议,感谢.