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'}
View on GitHubts
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
/* _____________ Your Code Here _____________ */typeFlip <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <{a : 'pi' },Flip <{pi : 'a' }>>>,Expect <NotEqual <{b : 'pi' },Flip <{pi : 'a' }>>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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' }>>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeFlip <T > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <{a : 'pi' },Flip <{pi : 'a' }>>>,Expect <NotEqual <{b : 'pi' },Flip <{pi : 'a' }>>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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' }>>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
// most populartypeFlip <T extendsRecord <string ,string|number|boolean>> = {[P in keyofT as `${T [P ]}`]:P }
ts
// most populartypeFlip <T extendsRecord <string ,string|number|boolean>> = {[P in keyofT as `${T [P ]}`]:P }