Javascript 如何确保typescript模块符合接口

Javascript 如何确保typescript模块符合接口,javascript,typescript,interface,module,Javascript,Typescript,Interface,Module,我正在为一些领域编写一个特定的内容。所以对于那些受支持的域,我只声明了一些函数,假设有一个 export function getContent(html: string): string {} 所以,我有许多文件与这个确切的接口,例如 export interface Domain { supportsHttps: boolean; getContent(html: string): string; } 然后为了简单起见(为了绘制受支持主机名和我的域文件的映射),我只需要

我正在为一些领域编写一个特定的内容。所以对于那些受支持的域,我只声明了一些函数,假设有一个

export function getContent(html: string): string {}
所以,我有许多文件与这个确切的接口,例如

export interface Domain {
    supportsHttps: boolean;
    getContent(html: string): string;
}
然后为了简单起见(为了绘制受支持主机名和我的域文件的映射),我只需要

然后我导入我的域列表

// index.ts
import * as url from 'url';
import domains from './domainsList';

const maybeDomain: Domain | undefined = domains[url.parse(someUrl).host];

if (maybeDomain) {
    // here I get proper autocompletion ...
    const content = maybeDomain.getContent(someHtml);
} else {
    throw new Error('domain not supported');
}
但是,如果我将接口中的函数名从getContent重构为getContents,那么实际上所有域文件中都没有任何编译错误


我想确保./domains/domainA.ts导出的结构符合我的域接口。我有办法做到这一点吗?

因为您实际上没有定义具有域类型的函数,所以编译器不会将两者链接在一起,因此不会出现错误

而且,接口比函数更适合

您可以通过定义类而不是函数来获得所有检查。像这样:

类AwesomeDomain实现域{
公共支持shttps:boolean;
getConten(html:string):string{
返回“”;
}
}

您可以找到一个完整的示例。

因为您实际上没有定义具有域类型的函数,所以编译器不会将两者链接在一起,因此不会出现错误

而且,接口比函数更适合

您可以通过定义类而不是函数来获得所有检查。像这样:

类AwesomeDomain实现域{
公共支持shttps:boolean;
getConten(html:string):string{
返回“”;
}
}

你可以找到一个完整的例子。

不完全是我想要的,但是它可以与一个简单的对象和接口一起工作,不需要类。不完全是我想要的,但是它可以与一个简单的对象和接口一起工作,不需要类。
// index.ts
import * as url from 'url';
import domains from './domainsList';

const maybeDomain: Domain | undefined = domains[url.parse(someUrl).host];

if (maybeDomain) {
    // here I get proper autocompletion ...
    const content = maybeDomain.getContent(someHtml);
} else {
    throw new Error('domain not supported');
}