I am trying to wrap my head around the concept of keyof in TypeScript.
My goal is to create a function that takes an object like { a : 1, b : 'anything'}
and should return something similar to { a: true , b: false }
, where the keys remain the same but the values are booleans.
However, when I attempt to write the function (as shown below)
function fn<K>(obj:K) : { [param:keyof K] : boolean } { /* ... */ }
... TypeScipt throws an error stating that param
must be a string or number.
This makes sense since K can be a map. How can I circumvent this error? Is there a way to declare that K is a plain JavaScript object with keys that are always strings? Using K extends {}
does not seem to work.