我正在处理模块,但遇到了我无法完全理解的场景。我已经像这样设置了一切:
import MyTesterImpl from "./MyTesterImpl";
declare module "./MyTesterImpl" {
interface MyTesterImpl {
augmented: boolean;
}
}
const main = async (): Promise<void> => {
let testy: MyTesterImpl = {
basicA: "hey",
basicB: "there"
} as MyTesterImpl;
testy.augmented = true;
};
main();
我将 MyTestImpl 定义为:
export default class MyTesterImpl {
public basicA: string;
public basicB: string;
constructor(a: string, b: string) {
this.basicA = a;
this.basicB = b;
}
showStuff() {
console.log(`${this.basicA} ${this.basicB}`);
}
}
使用这样定义的 tsconfig:
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
"skipLibCheck": true,
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"declaration": false,
"removeComments": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"baseUrl": ".",
},
"exclude": ["node_modules", "**/*.d.ts", "**/*.spec.ts"],
"include": ["./**/*.ts"]
}
即使在添加模块扩充以便将扩充字段附加到 MyTesterImpl 类之后,编译器仍然会抛出以下错误:
Property 'augmented' does not exist on type 'MyTesterImpl'.
您可以看到问题 here 的可重现示例.
我已经盯着它看了好几个小时了,但我无法找出错误一直存在的原因。我很肯定我可以在类和接口(interface)之间进行模块扩充,只要它们共享相同的名称,所以我认为这不是问题所在。我确保在声明要扩充的模块时指向类文件路径。
在我看来一切都准备就绪;我在这里错过了什么?
最佳答案
这是由于 TypeScript 中的一个错误,即导出为 default
的类不能是 merged进入;见microsoft/TypeScript#14080 . GitHub 中的问题已开放很长时间,并被标记为“积压”,因此我不指望它会很快得到修复。
A workaround mentioned in the issue是将类重新导出为命名导出,然后合并到that。它看起来像
// ./MyTesterImplRepackaged.ts
import MyTesterImpl from "./MyTesterImpl";
export { MyTesterImpl };
然后
// ./index.ts
import { MyTesterImpl } from "./MyTesterImplRepackaged";
declare module "./MyTesterImplRepackaged" {
interface MyTesterImpl {
augmented: boolean;
}
}
const main = async (): Promise<void> => {
let testy: MyTesterImpl = {
basicA: "hey",
basicB: "there"
} as MyTesterImpl;
testy.augmented = true; // okay
};
它不是很漂亮,但它似乎有效,至少对于您的示例代码而言。
关于javascript - 为什么属性 x 不存在于类型 Y 上,即使在模块扩充之后也是如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73784411/