首页 > 其他分享 >[Typescript] Create an Object Whose Keys Are Derived From a Union

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

时间:2022-12-11 22:14:48浏览次数:53  
标签:Whose Typescript string Keys ObjectOfKeys Union Expect type

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;
      }
    >
  >
];

 

标签:Whose,Typescript,string,Keys,ObjectOfKeys,Union,Expect,type
From: https://www.cnblogs.com/Answer1215/p/16974622.html

相关文章