#Constrain record keys to record types?

4 messages · Page 1 of 1 (latest)

rapid steeple
#

I am trying to work out whether there is way to have the keys of record by limited by the possible type value sit can take.

For example, I have a contraint: Record<string, unknown> property on my object, but there are a limited range of recognise values that can be used and their types correspond to a key:

type quantityConstraint = {
  min: number
  max: number
}

type availabilityConstraint = {
  from: Date
  to: Date
}

// with possible assigned data (each member is optional)
constraint: {
  quantity: {
    min: 1,
    max: 2
  },
  availability: {
    min: 1,
    max: 2
  }
}

I don't see any way of doing this with Record type, so I am wondering whether I am just missing something or wanting something that the language can't provide?

Edit: Looking at this, maybe going via an enum could work: https://www.typescriptlang.org/docs/handbook/enums.html

#

Constrain record keys to record types?

lucid cradle
#

i might have misunderstood the question, but why not this?

type YourObject = {
  constraint: {
    quantity?: quantityConstraint
    availability?: availabilityConstraint
  }
}
rapid steeple
#

I was imagining something more sophisticated, but this is certainly a reasonable approach.