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.

wkrueger
  • 1,281
  • 11
  • 21

1 Answers1

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.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299