Alex Rivera | Logout

Why does my TypeScript mapped type lose optionality when using keyof?

Asked 2026-02-14T10:30:00Z by Natalie Kim
18
I'm trying to create a mapped type that transforms all properties of an interface but preserves whether each property is optional. When I use [K in keyof T]: Transform the resulting type makes everything required. I expected the optionality modifier to carry over automatically...
Edit
Report

1 Answer

22
✔ Accepted
This is a known TypeScript behavior. Homomorphic mapped types (where you map over keyof T directly) do preserve modifiers, but only if you write it as { [K in keyof T]: ... }. If you're using a generic constraint like K extends keyof T in a separate type parameter, the compiler loses the modifier tracking. The fix is to use the built-in utility types: type MyMapped = { [K in keyof T]: Transform } which is homomorphic vs type MyMapped = { [P in K]: ... } which is not.
answered 2026-02-14T12:05:00Z by Alex Rivera

Your Answer