将当前模块声明为具有特定接口

Declare current module as having a particular interface

我有一个项目,里面有一个文件夹,每个文件夹都有一个模块,应该有一个特定的接口:

project/
  modules/
    A/index.ts
    B/index.ts
    C/index.ts

每个 index.ts 文件都应该遵循特定的接口。 像这样:

export const foo = ...
export const bar = ...

如何声明每个 index.ts 文件必须导出特定接口? 换句话说,我需要告诉 TypeScript module.exports 每个 index.ts 文件都必须遵守特定的接口。

我在 Github 上用 TypeScript / DefinitelyTyped 提交了一个问题:https://github.com/Microsoft/TypeScript/issues/19554

一般来说,尚不支持指定模块必须实现的类型,但您可以使用您在链接的 GitHub 问题中建议的约定。

好吧,它确实适用于导出表单,但无论类型是否存在,您都使用了无效的导出语法 (export {} as MyInterface)。

一种写法是

export interface MyInterface {
    id: number;
    name:string
}

const m: MyInterface = {
    id: 1
}

export = m;

我们可能会想把它写得更简洁一点

export = {id: 1} as MyInterface;

这是有效的语法,但充当类型断言,而不是实现要求,因此

export = {} as MyInterface;

还有类型检查。这使得第一种形式更可取。