0

im trying to understand keyof.

I want to describe a function which receives an object { a : 1, b : 'anything'} and should return something like { a: true , b: false } (same keys, but always boolean values).

But when I write (example)

function fn<K>(obj:K) : { [param:keyof K] : boolean } { /* ... */ }

... TS says me param must be string or number.

That makes sense, since K can be a map. How could I avoid that error? How could I declare that K is a plain JS object (so its keys are always string)? K extends {} doesnt work.

1 Answer 1

2

It should be:

function fn<K>(obj: K): { [P in keyof K]: boolean } { /* ... */ }

As shown in the mapped types section of the keyof feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.