Home > front end >  typing toPrimitives interface
typing toPrimitives interface

Time:05-21

I have an interface like this:

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

And I implement it like this:

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

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

This also forces me to return the key "toPrimitives"

Does anyone know how to avoid this?

CodePudding user response:

You could modify the return type to exclude any function types:

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

  • Related