ThomasReggi
ThomasReggi

Reputation: 59345

Object typing where value is array of keys or empty array

I am looking to type an object like this:

const example = {
  'meow': [],
  'woof': [],
  'quack': [],
  'all': ['meow', 'woof', 'quack'],
  'meowWoof': ['meow', 'woof'],
}

Above, would be valid. You see it is meta because the values, have to be arrays which values are keys in the object itself.

However this would not because DOGS is not a key.

const example = {
  'meow': [],
  'woof': [],
  'quack': [],
  'all': ['meow', 'DOGS', 'quack'],
  'meowWoof': ['meow', 'woof'],
}

I'd be OK with wrapping this object in a function to get the typing working.

Is this possible?

Upvotes: 2

Views: 30

Answers (1)

jcalz
jcalz

Reputation: 327774

I'd use a generic helper function like this:

const asExample = <T extends Record<keyof T, Array<keyof T>>>(t: T) => t;

It behaves how you seem to want it:

const example = asExample({
    'meow': [],
    'woof': [],
    'quack': [],
    'all': ['meow', 'woof', 'quack'],
    'meowWoof': ['meow', 'woof'],
}); // okay

const badExample = asExample({
    'meow': [],
    'woof': [],
    'quack': [],
    'all': ['meow', 'DOGS', 'quack'],  // error here
    'meowWoof': ['meow', 'woof'],
});

Hope that helps. Good luck!

Link to code

Upvotes: 1

Related Questions