0

I want to define a generic function accepting any type or Notification object. This object has a method property. the function should accept any output that has a method property and each output has it's own method type. I need to return a type that This is the class:

export interface Notification {
  readonly timestamp: number;
  method: string;
}

export interface MyNotification extends Notification {
  readonly timestamp: number;
  method: 'Method1' | 'Method2';
}

export function makeNotification<T, U extends { method: T }>(method: T): U {
  const timestamp = new Date().getTime();

  // ------------------This line has error
  return {
    timestamp,
    method,
  };
}

export function makeMyNotification(info): MyNotification {
  return makeNotification('Method1') as MyNotification;
}

But there is a typescript error in the function:

Type '{ timestamp: number; method: T; }' is not assignable to type 'U'. 'U' could be instantiated with an arbitrary type which could be unrelated to '{ timestamp: number; method: T; }'.ts(2322)

rostamiani
  • 2,859
  • 7
  • 38
  • 74
  • Does it need to be generic? Wouldn't `makeNotification(method: string): Notification` do? – Nadia Chibrikova Aug 11 '21 at 21:00
  • It does, but there is no type safety then. I need to define a method type for each class. – rostamiani Aug 12 '21 at 00:41
  • As you return an object with the same shape for any input, it's not clear from your example what sort of type safety you require, maybe you can include examples of how you plan to use the method? – Nadia Chibrikova Aug 12 '21 at 20:09

0 Answers0