This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
61. implement Prefix<T, P>
To solve this problem, we can use mapped types and template literal types in TypeScript. Here's the implementation:
type Prefix<T, P extends string> = { [K in keyof T as `${P}_${K}`]: T[K];};
Explanation:
- We define a mapped type
Prefix<T, P extends string>
. - We use the
keyof
keyword to iterate over all the keys inT
. - We use the
as
keyword followed by a template literal type${P}_${K}
to prefix the key names. - Inside the square brackets, we map each key
K
to the new prefixed key${P}_${K}
and its corresponding valueT[K]
.
Now, let's test the implementation:
type A = Prefix<{ a: 'bfe', b: 'dev'}, 'BFE'>;// { BFE_a: 'bfe', BFE_b: 'dev'}// Test caseconst a: A = { BFE_a: 'bfe', BFE_b: 'dev'};
The type A
is expected to be { BFE_a: 'bfe', BFE_b: 'dev'}
.
Hope this helps! Let me know if you have any other questions.