如何在泛型类型别名中访问类型参数的静态属性

时间:2019-06-04 20:58:42

标签: angular typescript

我正在尝试创建类型别名,在给定角度服务类的情况下,该别名是同一类的交集,并且同时使其所有函数属性的类型均为Unable to determine the serialization information for x => x.PetId.Value

也许很难遵循,所以这里有个例子。给定一个类<original function type> & jest.Mock

AuthenticationService

我想创建一个与export class AuthenticationService { numberProp: number; static staticFunc() { return 'typeof AuthService'; } login(username: string, password: string): Observable<boolean> { return of(false); } getAuthSources(): string[] { return []; } isSourceAuthorized(source: string) { return true; } } 完全一样的类型,但是例如AuthenticationService的类型为login

到目前为止,我所做的是:

((string, string) => Observable<boolean>) & jest.Mock

我的问题是试图使我的类型别名也包含type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T]; type MockService<aService> = (aService & Record<FunctionPropertyNames<aService>, jest.Mock>) extends infer P ? P : never; // the extends infer P part is to get a more explicit type rather than a type alias that hides the implementation 。我无法做类似staticFunc的事情,因为Record<FunctionPropertyNames<typeof aService...。我可以使用显式aService is being used as a value here,但不能在类型参数typeof AuthenticationService上使用。

当前解决方法

通过提供aService作为类型参数,并在类型别名中使用typeof AuthenticationService,我能够将静态方法添加到新类型:

InstanceType<>

是否可以编写这种方式,以便在键入这些交集类型以包括静态属性时使用interface Constructor<T = any> { new(...args: any[]): T; } type MockService<aService extends Constructor> = ( // need to add original types of static functions & InstanceType<aService> & Record<FunctionPropertyNames<InstanceType<aService>>, jest.Mock> & Record<FunctionPropertyNames<aService>, jest.Mock> ) extends infer P ? P : never; 而不是AuthenticationService

0 个答案:

没有答案
相关问题