输入到Primitives接口

typing toPrimitives interface

我有一个这样的界面:

interface AggregateRoot<Primitives> {
  toPrimitives(): { [key in keyof Primitives]: any }
}

我是这样实现的:

class Person implements AggregateRoot<Person> {
  public name
  public age

  toPrimitives(): { [key in keyof Person]: any } {
    return {
      name: 'Tom',
      age: 10
    }
  }
}

这也迫使我return键“toPrimitives”

有谁知道如何避免这种情况?

您可以修改 return 类型以排除任何函数类型:

interface AggregateRoot<Primitives> {
  toPrimitives(): { 
    [K in keyof Primitives as Primitives[K] extends Function ? never : K]: any 
  }
}

toPrimitives(): { 
  [key in keyof Person as Person[key] extends Function ? never : key]: any 
} {
  return {
    name: 'Tom',
    age: 10
  }
}

Playground