[英]Declare an interface where all properties conform to a type, WITHOUT widening the interface
我正在尋找一種聲明接口屬性符合特定類型而不擴展該接口的方法。
例如:
export interface ServiceDeclaration {
[key: string]: (params?: any) => Promise<any>;
}
interface MyService extends ServiceDeclaration {
doThing(params?: { id: string }): Promise<string>;
}
到現在為止還挺好。 這將斷言MyService
中的所有屬性都是帶有最多一個參數的異步函數。
但是,這也導致MyService
也被擴展為包括ServiceDeclaration
的索引類型。 例如:
// This should result in an error of 'notAThing' being a key of
// MyService. Instead it resolves to (params?: any) => Promise<any>
export type Foo = Pick<MyService, 'notAThing'>;
是否有斷言MyService
遵守ServiceDeclaration
而不擴展其類型的干凈方法? 而且,可以做到這一點而無需跳過笨拙的箍(例如通過仿函數傳遞它,或導出其他類型)嗎?
一種方法, 做工作,但很尷尬的,是添加一個額外的類型聲明(並將其導出為其他未使用的類型):
export type ServiceDeclaration<TKey extends string = string> = {
[Key in TKey]: (params?: any) => Promise<any>;
}
export type IsValidServiceDeclaration<TService extends Record<keyof TService, (params?: any) => Promise<any>>> = TService;
interface MyService {
doThing(params?: { id: string }): Promise<string>;
doAnotherThing(params?: { id: string }): string;
}
export type MyServiceIsValid = IsValidServiceDeclaration<MyService>
我正在尋找比這更好的東西。
export type ServiceDeclaration<T> = {
[K in keyof T]: (params?: any) => Promise<any>;
};
interface MyService extends ServiceDeclaration<MyService> {
doThing(params?: { id: string }): Promise<string>;
}
export type Foo = Pick<MyService, 'notAThing'>; // Type '"notAThing"' does not satisfy the constraint '"doThing"'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.