我有許多配接器都是從這樣的介面實作的
export interface IAdapter {
doSomething(): void;
}
并且實作的類看起來與您期望的非常相似和基本
export default class AdapterA implements IAdapter {
private _property: string;
constructor(someProperty: string) {
this._property = someProperty;
}
}
我有一個配接器工廠,想像這樣使用它
export abstract class AdapterFactory {
static async getInstance(name: string) Promise<IAdapter> {
switch(name) {
case 'a':
return import('./adapters/adapter-a');
case 'b':
return import('./adapters/adapter-b');
}
}
}
在呼叫工廠的代碼之后,我希望能夠使用回傳的模塊來實體化配接器的新實體,例如
const adapterModule = await getInstance('a');
const myNewAdapter = new adapterModule('prop');
myNewAdapter.doSomething();
當我在工廠內嘗試時,我得到:
Type 'typeof import("/[absolute path]/adapters/AdapterA")' provides no match for the signature 'new (someProperty: string): IAdapter'
所以我嘗試添加 new 的定義(我不喜歡),如下所示:
export interface IAdapter {
new(someProperty: string): IAdapter;
doSomething(): void;
}
現在我得到:
This expression is not constructable.
任何人都可以提供的任何幫助都會受到極大的歡迎
uj5u.com熱心網友回復:
匯入的建構式應該從default:
const { default: adapterModule } = await getInstance('a');
我們需要 default 的原因是,從 webpack 4 開始,在匯入 CommonJS 模塊時,匯入將不再決議為 module.exports 的值,而是會為 CommonJS 模塊創建一個人工命名空間物件。
不相關的小建議:
- 重命名
getInstance->getConstructor - 將回傳型別更改為
Promise<IAdapterConstructor>
在哪里IAdapterConstructor:
interface IAdapterConstructor {
new(someProperty: string): IAdapter;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343868.html
