通用接口
export interface BaseService {
getById<T extends number | string>(id: T): Promise<SomeType>;
}
还有,实施
export class AService implements BaseService {
async getById(id: number): Promise<SomeType> {
// logic
}
//Other functions will be implemented here
}
而且,我得到的错误:
Property 'getById' in type 'AService' is not assignable to the same property in base
type 'BaseService'.
Type '(id: number) => Promise<SomeType>' is not assignable to type '<T extends
string | number>(id: T) => Promise<SomeType>'.
Types of parameters 'id' and 'id' are incompatible.
Type 'T' is not assignable to type 'number'.
Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.ts(2416)
我试过几件事:
getById<T extends number>(id: T): Promise<SomeType>; //This works, But I would have some methods with id type string
还有
getById<T>(id: T): Promise<SomeType>; //still compains
我一直在关注Documentation。但是,没有遇到任何类似的事情。
非常感谢任何想法或想法或任何文档!!
1条答案
按热度按时间zujrkrfu1#
getById<T extends number | string>(id: T): Promise<SomeType>
泛型方法是非常没有意义的,它或多或少等价于仅仅声明一个getById(id: number | string): Promise<SomeType>
类型的方法。我猜你真正想要的是