1

1. Array of Strings -> Union of Strings (It works)

I saw a solution creates a union of string literals from an array of strings.

const keys = ["cat", "dog"] as const;

type Keys = typeof keys[number]; // "name" | "age"

2. Array of Strings -> Union of Objects (Is it possible?)

My question is if it's possible to create a union of objects from an array of strings? The code below works, I just want to shorten the SET_PROPERTY_PAYLOAD with something like keyof IObject and generate a union of object types from there.

interface IObject = {
  id: string;
  name: string;
  age: number;
}

// Is it possible to shorten this type using typescript's primitives
type SET_PROPERTY_PAYLOAD = 
| {
    id: string;
    propertyName: "id"; // keyof IObject at index 0
    value: string; // IObject["id"]
  }
| {
    id: string;
    propertyName: "name"; // keyof IObject at index 1
    value: string; // IObject["name"]
  }
| {
    id: string;
    propertyName: "age"; // keyof IObject at index 2
    value: number; // IObject["age"]
  };

My goal for this is to narrow the type of value by inferring from the current value of propertyName.

1 Answer 1

3

You want a mapped type.

interface IObject {
  id: string;
  name: string;
  age: number;
}

type SET_PROPERTY_PAYLOAD = {
    [K in keyof IObject]: {
        id: string,
        propertyName: K,
        value: IObject[K]
    }
}[keyof IObject]

This type maps over the keys in IObject and create a new object type for each key.

SET_PROPERTY_PAYLOAD should then be exactly equivalent to your long form version above.

See Playground

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

2 Comments

Wow that was quick. Thank you Alex! I read MappedTypes and initially thought it was only for making new properties K inside an object SET_PROPERTY_PAYLOAD. I just realized you could actually still use [keyof IObject]. Thank you for this! You're a big help!
Your assumption is correct. With type logic like this, there is often many steps of transformation, and each type is just one step. Type transformations can be very liquid :)

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.