srhuevo
srhuevo

Reputation: 420

typing toPrimitives interface

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?

Upvotes: 1

Views: 62

Answers (1)

Tobias S.
Tobias S.

Reputation: 23835

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

Upvotes: 1

Related Questions