TypeScript: extracting keys of union type (keyof UnionType)

When you want to extract keys of union type in TypeScript. This post helps you.

export type Attribute1 = {
  colors: string[];

export type Attribute2 {
  categories: string[];

export type Attributes = Attribute1 | Attribute2;

In case you want to use keys of either Attribute1or Attribute2 in a commonly used function, you would take the following approach.

// type Attributes = Attribute1 | Attribute2;
const func = (attributeKey: keyof Attributes) => {
  // do something

However, it does not work.
In that case, this works correctly.

Wrapper type

export type KeysOfUnion<T> = T extends T ? keyof T: never;

AvailableKeys will basically be keyof Attribute1 | keyof Attribute2 so it will be ''colors '' | "categories"

type AvailableKeys = KeysOfUnion<Attributes>;