wkrueger
wkrueger

Reputation: 1373

Typescript + keyof. Declaring an object transformation

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.

Upvotes: 0

Views: 632

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164137

It should be:

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

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

Upvotes: 2

Related Questions