Richard Fernandez
Richard Fernandez

Reputation: 599

Get all keys from array of (different) objects type

I have a type FooBar, that contains objects with different props. I want to get the keys from all objects. I thought that could be obtained by using keyof FooBar[number]; but it only returns the common keys.

type FooBar = [
  {
    foo: "hello";
    bar: "goodbye";
  },
  {
    foo: "hi";
    bar: "goodbye";
    fizz: "buzz";
  }
];

type FooBarKeys = keyof FooBar[number];

// type FooBarKeys = "foo" | "bar"

How do I get all keys for all the objects?

Upvotes: 0

Views: 218

Answers (1)

hansmaad
hansmaad

Reputation: 18915

type Index<T> = {[k in keyof T]: k}  // ["0", "1"]
type Props<T> = {[k in keyof Index<T>]: keyof T[k]}  // ["foo"|"bar", "foo"|"bar"|"fizz"]
type Keys = Props<FooBar>[number];

Playground

Upvotes: 1

Related Questions