代码之家  ›  专栏  ›  技术社区  ›  user1595858

类型“”中的属性“method”不可赋值给基类型中的同一属性

  •  0
  • user1595858  · 技术社区  · 3 年前

    我们用可选实现了一个泛型类型,它使用默认类型,否则在运行方法时应该使用类型集。

    type Test = {
      a: number;
      b: string;
    }
    interface IApple {
      // we can call it as `method()` fallbacks to `Test` type or with custom type like `method<AnotherType>()`
      method<T=Test>(): Promise<T> 
    }
    
    

    现在,当我写这样一节课的时候。

    class Apple implements IApple {
       method() {
        return Promise.resolve({
            a: 10, 
            b: 'test',
         } as Test)
    }
    
    

    获取类型错误

    Property 'method' in type 'Apple' is not assignable to the same property in base type 'IApple'.
      Type '() => Promise<{ a: number; b: string; }>' is not assignable to type '<T = Test>() => Promise<T>'.
        Type 'Promise<{ a: number; b: string; }>' is not assignable to type 'Promise<T>'.
          Type '{ a: number; b: string; }' is not assignable to type 'T'.
            'T' could be instantiated with an arbitrary type which could be unrelated to '{ a: number; b: string; }'.
    
    1 回复  |  直到 3 年前