[英]How can I declare type of an ES6 module in Typescript?
I have a generic interface for a repository like this. 我有一个像这样的存储库的通用接口。
export interface IBaseRepository<T> {
create(model: T): T;
edit(model: T): T;
read(): T
}
I'm trying to implement this repository interface in a functional module like this (since it's basically a stateless singleton). 我试图在这样的功能模块中实现这个存储库接口(因为它基本上是一个无状态单例)。
// user-repository.ts
export function create(model: IUser): IUser { ...code }
export function edit(model: IUser): IUser { ...code }
export function read(): IUser { ...code }
Is there any way to ensure that IBaseRepository
is implemented in UserRepository
. 有没有办法确保在
IBaseRepository
中实现UserRepository
。 Or do I have to always implement the repository as a class and export an instantiated singleton? 或者我是否必须始终将存储库实现为类并导出实例化的单例?
You can bundle all functions into an object and have that exported. 您可以将所有函数捆绑到一个对象中并将其导出。
Something like this: 像这样的东西:
import { IBaseRepository } from './master';
// user-repository.ts
export function create(model: string): string { return ''; }
export function edit(model: string): string { return ''; }
export function read(): string { return ''; }
export const repository: IBaseRepository<string> = { create, edit, read };
And use it like you would use anything else that module exports: 并使用它就像你将使用模块导出的任何其他东西:
import { repository } from './repo';
repository.create('test');
Or use the export default to export the functions directly if you want to have that type for the default module export. 或者,如果要为默认模块导出具有该类型,请使用导出默认值直接导出函数。
import { IBaseRepository } from './master';
// user-repository.ts
export function create(model: string): string { return ''; }
export function edit(model: string): string { return ''; }
export function read(): string { return ''; }
export default { create, edit, read } as IBaseRepository<string>;
And import the module to get it or import the functions separately : 并导入模块以获取它或单独导入功能:
import repo, { create } from './repo';
repo.create('test');
You can still import each function independently of course. 您仍然可以独立导入每个功能。
Note use types according to your example I just tried to keep things simpler. 注意根据你的例子使用类型我只是试图让事情更简单。
How about this? 这个怎么样?
interface IFoo {
foo(): boolean;
bar();
}
namespace Foo {
export function foo() {
return 42;
}
}
declare type assert<T, K extends T> = {};
declare const check1: assert<IFoo, typeof Foo>;
We get a nice error on the check1: 我们在check1上得到一个很好的错误:
Type 'typeof Foo' does not satisfy the constraint 'IFoo'.
Types of property 'foo' are incompatible.
Type '() => number' is not assignable to type '() => boolean'.
Type 'number' is not assignable to type 'boolean'.
My example has an inline module, but it should be similar to assert an external module using a import * as Foo from './foo';
我的示例有一个内联模块,但它应该类似于使用
import * as Foo from './foo';
断言一个外部模块import * as Foo from './foo';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.