0

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?

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.