简体   繁体   中英

TypeScript Generics type '{ result: true }' is not assignable to type 'T'

Attempting to use generic types but I can't seem to get it to work, though I'm sure it's something simple. Here's a basic example

// some module
type TMainResponse<T> = {
  data: T;
};

interface Foo {
  func<T>(): Promise<TMainResponse<T>>;
}

// local module
type TLocalResponse = {
  result: boolean;
};

const obj: Foo = {
  async func<TLocalResponse>() {
    return {
      data: {
        result: true
      }
    };
  }
};

(async function () {
  await obj.func();
});

The result of which is

Type 'Promise<{ data: { result: boolean; }; }>' is not assignable to type 'Promise<TMainResponse<T>>'.
    Type '{ data: { result: boolean; }; }' is not assignable to type 'TMainResponse<T>'.
      Types of property 'data' are incompatible.
        Type '{ result: boolean; }' is not assignable to type 'T'.

16   async func<TLocalResponse>() {
           ~~~~

  src/test.ts:7:3
    7   func<T>(): Promise<TMainResponse<T>>;
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The expected type comes from property 'func' which is declared here on type 'Foo'

Am I doing something wrong, or did I just misunderstand the usage of generics?

Am I doing something wrong, or did I just misunderstand the usage of generics?

This interface is at least a bit atypical:

interface Foo {
  func<T>(): Promise<TMainResponse<T>>;
}

The Foo has no type argument, but <T> is used in two places within the body. To be honest I'm not really sure how that's supposed to work (there's no compile error so it's likely working by design -- would be interested if someone can weigh in here) but if you change the interface to hold the type argument:

interface Foo<T> {
  func(): Promise<TMainResponse<T>>;
}

And the usage accordingly:

const obj: Foo<TLocalResponse> = {
  async func() {
    return {
      data: {
        result: true
      }
    };
  }
};

Then the whole thing works fine .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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