跳到主要内容

Flip

介绍

实现just-flip-object类型.例如:

ts
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'}
ts
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'}
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type Flip<T> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<{ a: 'pi' }, Flip<{ pi: 'a' }>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<NotEqual<{ b: 'pi' }, Flip<{ pi: 'a' }>>>,
Expect<Equal<{ 3.14: 'pi', true: 'bool' }, Flip<{ pi: 3.14, bool: true }>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<{ val2: 'prop2', val: 'prop' }, Flip<{ prop: 'val', prop2: 'val2' }>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type Flip<T> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<{ a: 'pi' }, Flip<{ pi: 'a' }>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<NotEqual<{ b: 'pi' }, Flip<{ pi: 'a' }>>>,
Expect<Equal<{ 3.14: 'pi', true: 'bool' }, Flip<{ pi: 3.14, bool: true }>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<{ val2: 'prop2', val: 'prop' }, Flip<{ prop: 'val', prop2: 'val2' }>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// most popular
 
type Flip<T extends Record<string ,string|number|boolean>> = {
[P in keyof T as `${T[P]}`]: P
}
 
ts
// most popular
 
type Flip<T extends Record<string ,string|number|boolean>> = {
[P in keyof T as `${T[P]}`]: P
}
 
view more solutions