簡體   English   中英

聲明一個接口,其中所有屬性均符合類型,而無需擴展接口

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM