0

我想定义一个接受任何类型或通知对象的通用函数。这个对象有一个method属性。该函数应该接受任何具有方法属性的输出,并且每个输出都有自己的方法类型。我需要返回一个类型,这是类:

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;
}

但是函数中有一个打字稿错误:

输入'{时间戳:数字;方法:T;}' 不可分配给类型 'U'。'U' 可以用与 '{ timestamp: number; 无关的任意类型实例化。方法:T;}'.ts(2322)

4

0 回答 0