繁体   English   中英

Typescript 通用接口 function 参数类型推断错误

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM