rostamiani
rostamiani

Reputation: 3265

How can I make a generic function that accepts a specific property of the returning custom interface

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)

Upvotes: 0

Views: 82

Answers (0)

Related Questions