Typescript類型體操 - Flip

題目

中文

實現一個 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;
};

在線演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章