[Typescript] Create an Object Whose Keys Are Derived From a Union

Let's say we have 

type TemplateLiteralKey = `${"user" | "post" | "comment"}${"Id" | "Name"}`;

 

We want to make a type

type ObjectOfKeys = unknown;

 

In order to get result: assume the object value should be string type for each prop

type tests = [
  Expect<
    Equal<
      ObjectOfKeys,
      {
        userId: string;
        userName: string;
        postId: string;
        postName: string;
        commentId: string;
        commentName: string;
      }
    >
  >
];

 

I wrote like this:

type ObjectOfKeys = { [Key in TemplateLiteralKey]: string };

It is also fine to write like this:

type ObjectOfKeys = Record<TemplateLiteralKey, string>;

 

 

Another example:

import { Equal, Expect } from "../helpers/type-utils";

type Event = `log_in` | "log_out" | "sign_up";

type ObjectOfKeys = Record<Uppercase<Event>, string>;

type tests = [
  Expect<
    Equal<
      ObjectOfKeys,
      {
        LOG_IN: string;
        LOG_OUT: string;
        SIGN_UP: string;
      }
    >
  >
];

 

posted @ 2022-12-11 21:57  Zhentiw  阅读(25)  评论(0编辑  收藏  举报