[英]How to make sure a typescript module conforms to an interface
我正在為某些域編寫特定的內容抓取工具。 所以對於那些支持的域,我只聲明了一些函數,假設有一個
export function getContent(html: string): string {}
所以,我有很多具有這個確切界面的文件,例如......
export interface Domain {
supportsHttps: boolean;
getContent(html: string): string;
}
然后為了簡單起見(制作支持的主機名和我的域文件的映射),我只是
// domainsList.ts
import * as domainA from './domains/domainA';
export default {
"www.domainA.com": domainA,
}
然后我導入我的域列表
// 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 導出的結構符合我的 Domain 接口。 我有辦法嗎?
由於您實際上並未定義具有 Domain 類型的函數,因此編譯器不會將它們兩者鏈接在一起,因此不會出現錯誤。
此外, Domain接口比函數更適合類。
您可以通過定義類而不是函數來獲得所有檢查。 像這樣:
class AwesomeDomain implements Domain {
public supportsHttps: boolean;
getConten(html: string): string {
return '';
}
}
您可以在此處找到完整示例。
這是我的解決方案,只要您通過索引文件導出專門公開所有導入。
模塊/index.ts
import * as A from "./A";
import * as A from "./B";
// type definitions
export type MyFunc = (args: any[]) => any;
export type MyCollection = {
[key: string]: MyModule,
}
export interface MyModule {
KEY: string;
EXAMPLE_ARRAY: string[];
someFn: MyFunc;
}
export const COMMANDS = {
[A.KEY]: A,
[B.KEY]: B,
} as MyCollection;
模塊/A.ts
import { MyFunc } from ".";
export const KEY = "some-key";
export const EXAMPLES = [
"hello",
"world",
]
export const someFn: CommandFn = async (args: any[]) => {
return ''
};
如果您取消注釋其中一個導出:
Conversion of type '{ "A": typeof A; "B": typeof B; }' to type 'MyCollection' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Property '[A.KEY]' is incompatible with index signature.
Property 'someFn' is missing in type 'typeof import("...") but required in type 'MyModule'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.