首页 > 其他分享 >Typescript类型体操 - Flip

Typescript类型体操 - Flip

时间:2022-10-02 17:23:54浏览次数:65  
标签:Typescript false just object Flip 体操 type

题目

中文

实现一个 just-flip-object 类型

示例:

Flip<{ a: 'x'; b: 'y'; c: 'z' }>; // {x: 'a', y: 'b', z: 'c'}
Flip<{ a: 1; b: 2; c: 3 }>; // {1: 'a', 2: 'b', 3: 'c'}
Flip<{ a: false; b: true }>; // {false: 'a', true: 'b'}

English

Implement the type of just-flip-object. Examples:

Flip<{ a: 'x'; b: 'y'; c: 'z' }>; // {x: 'a', y: 'b', z: 'c'}
Flip<{ a: 1; b: 2; c: 3 }>; // {1: 'a', 2: 'b', 3: 'c'}
Flip<{ a: false; b: true }>; // {false: 'a', true: 'b'}

No need to support nested objects and values which cannot be object keys such as arrays

答案

type Flip<T> = {
    [K in keyof T as T[K] extends
        | string
        | number
        | bigint
        | boolean
        | null
        | undefined
        ? `${T[K]}`
        : never]: K;
};

在线演示

标签:Typescript,false,just,object,Flip,体操,type
From: https://www.cnblogs.com/laggage/p/type-challenge-flip.html

相关文章