![]() ![]() Be aware that any objects your function receives as parameters might have additional keys. ![]() ![]() Use let k: keyof T and a for-in loop to iterate objects when you know exactly what the keys will be.The latter is more generally appropriate, though the key and value types are more difficult to work with. The former is appropriate for constants or other situations where you know that the object won't have additional keys and you want precise types. If you want to iterate over the keys and values in an object, use either a keyof declaration ( let k: keyof T) or Object.entries. Hopefully this doesn't happen in a nonadversarial environment (you should never add enumerable properties to Object.prototype), but it is another reason that for-in produces string keys even for object literals. This code runs fine, and yet TypeScript flags an error in it. Reading through this item again, I'd add that this is all a good reason to consider using an ES6 Map instead of an object to store key/value pairs! The difficulty results from a combination of the quirks of JavaScript objects and duck typing. Iterating over the keys and values in an object is a common operation that's surprisingly hard to write without type assertions in TypeScript. ![]()
0 Comments
Leave a Reply. |