如何避免在Visual Studio代码中需要//@ts-ignore对自定义窗口字段的分配?



默认情况下,TypeScript编译器(以及Visual Studio扩展)会显示像这样分配自定义Window字段的代码的错误:

window.inv = inv;
window.NPC = NPC;

我知道window对象默认没有invNPC这样的字段。对每一行这样的代码使用ts-ignorets-expect-error注释似乎是非常错误的。有没有一种很好的方法可以在不触及任何其他ts-check功能的情况下从显示中删除这种错误?

添加模块声明文件,并使用接口合并来扩展Window接口。

下面是一个例子:

index.ts:

window.foo = 42;
window.bar = "hello world";

index.d。Ts(模块声明文件):

interface Window {
foo: number;
bar: string;
}

你可以在这里阅读更多关于模块声明文件:
https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html.



https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces.

最新更新