Search code examples
functiontypescriptgenericsecmascript-5nested-generics

Typescript - generics in function property does not get resolved


i'm pretty new to typescript and i'm trying to play with nested generics. By now I can't make them work as i would expect, probably i'm missing something obvious. Here is my sample code:

type GenericServiceResponse<T> = {
  status: number;
  payload: T;
}

type myServicePayload = {
  name: string;
  surname: string;
}

type myServiceResponse = GenericServiceResponse<myServicePayload>;

class GenericServiceRequest {
  callback?: <T>(data:T) => void;
}

let request = new GenericServiceRequest();

request.callback = <myServiceResponse>(data:myServiceResponse) => {
  console.info(data.payload.name);
};

The output of the tsc compiler (target es5) is:

main.ts(20,23): error TS2339: Property 'payload' does not exist on type 'myServiceResponse'.


Solution

  • Try it this way. The main problem were the casts you had in the definition of callback and where it is assigned. Besides, the class needs to be generic, too. Otherwise, Typescript does not know what T means.

    type GenericServiceResponse<T> = {
      status: number;
      payload: T;
    }
    
    type myServicePayload = {
      name: string;
      surname: string;
    }
    
    type myServiceResponse = GenericServiceResponse<myServicePayload>;
    
    class GenericServiceRequest<T> {
      callback?: (data:T) => void;
    }
    
    let request = new GenericServiceRequest<myServiceResponse>();
    
    request.callback = data => {
      console.info(data.payload.name);
    };
    

    As you see, now you don't have to speficy the type of data in the las sentence, it`s inferred by the definition of request.