我正在尝试为具有 new
的库添加类型能发挥作用,但发现真的很难做到。
简单地说:
export default function Api<T>(opts?: Settings): Api<T>;
我得到“只能用'new'关键字调用一个void函数”。我知道 new
关键字在声明文件中有效,例如:export default interface Api {
new<T=any>(opts?: Settings): Api<T>
}
这只是导出一个类型,正如编译器所说:“只引用一个类型,但在这里被用作一个值”。我这里不能使用类,因为 API 可以通过来自其他文件的插件进行扩展,并且类型声明合并不适用于类(我希望其他文件添加的方法能够通过他们自己的打字文件也是如此)。
我不知所措 - 有什么想法吗?
最佳答案
我无法得到与您完全相同的错误,但我能够在 TypeScript 4.3.5 中拼凑一些东西,使您的默认导出成为(可扩展的)接口(interface),您仍然可以定期调用并用作构造函数:
api.d.ts
interface Settings {
setting?: string;
}
declare interface Api<T> {
getValue(): T;
<T>(opts?: Settings): Api<T>;
new<T>(opts?: Settings): Api<T>;
}
declare const Api: Api<any>;
export default Api;
index.ts import Api from './api';
// Augmentation the interface
declare module './api' {
export default interface Api<T> {
newField: number;
}
}
// Test the default export as Api instance
Api.getValue();
console.log(Api.newField);
// See if we can call/new the Api instance
const api = new Api<number>();
const api2 = Api<number>();
const api3: Api<number> = null!;
// Test the created instance as Api instance
const value: number = api.getValue();
console.log(api.newField);
Api
的类型值为 Api<any>
而api
的类型/api2
/api3
都是Api<number>
.我们可以使用 .getValue()
在所有这些上,以及用例如增强它.newField
然后我们可以从所有这些属性中读取属性。基本上自
declare interface
创建只是一个类型,我添加了一个 declare const
还创建导出的实际值。类似于 declare class
将类实例的接口(interface)以及实际类作为值导出。我用了两个 declares
后跟一个 export default
因为 TS 不允许您导出两个默认值,即使一个是纯粹的类型,另一个是纯粹的值。
关于typescript - 从 TypeScript 声明文件中导出 newable 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68455958/