我试图将类型定义添加到应该作为类的globalThis
上的变量。在JavaScript中:
globalThis.X = class {
...
}
我在为globalThis对象添加类型定义以允许此工作时遇到麻烦。
declare global {
module globalThis {
// Doesn't work. TypeScript error in declaration file.
var X = (class {
...
})
// Doesn't work. TypeScript error on usage.
class X {
...
}
}
}
const x = new globalThis.X();
console.log(x.value); // This works and will return the actual value on x.
参见codesandbox复制示例。
在TypeScript中,通过在函数定义前添加new
,它将充当构造函数。在您的示例中:
declare global {
module globalThis {
interface XType {
value: number;
}
var X: new (x?: number, y?: number) => XType;
}
}
那么当你尝试使用new globalThis.X()
时,你应该得到一个类型安全的变量作为XType
类型的输出。