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.

4

1 回答 1

2

它应该是:

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

keyof 功能的映射类型部分所示。

于 2017-02-06T01:03:13.643 回答