[英]Typescript generic interface function argument type inference error
通用接口
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 。 但是,沒有遇到過類似的事情。
非常感謝任何想法或想法或任何文檔!
getById<T extends number | string>(id: T): Promise<SomeType>
getById<T extends number | string>(id: T): Promise<SomeType>
泛型方法是毫無意義的,這或多或少等同於只聲明一個類型為getById(id: number | string): Promise<SomeType>
的方法。
我懷疑你真正想要的是
export interface BaseService<T extends number | string> {
getById(id: T): Promise<SomeType>;
}
export class AService implements BaseService<number> {
// ^^^^^^^^
async getById(id: number): Promise<SomeType> {
…
}
…
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.