How can I declare an ES6 module type in Typescript?

I have a common interface for such a repository.

export interface IBaseRepository<T> {
    create(model: T): T;
    edit(model: T): T;
    read(): T
}

I am trying to implement this repository interface in a function module like this (since this is basically stateless syntax).

// user-repository.ts
export function create(model: IUser): IUser { ...code }

export function edit(model: IUser): IUser { ...code }

export function read(): IUser { ...code }

Is there a way to guarantee that it is IBaseRepositoryimplemented in UserRepository. Or do I always need to execute the repository as a class and export a singleton instance?

+4
source share
2 answers

You can associate all functions with an object and export it.

Something like that:

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 as if you were using anything else that exports the module:

import { repository } from './repo';

repository.create('test');

, , , .

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>;

, :

import repo, { create } from './repo';

repo.create('test');

.

. .

+1

?

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>;

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'.

, import * as Foo from './foo';

+1

Source: https://habr.com/ru/post/1683821/


All Articles