From a02ef7023f2fb513dc35d8de35be23b926ec82e3 Mon Sep 17 00:00:00 2001 From: Jake Ginnivan Date: Sat, 31 Dec 2016 11:14:14 +0800 Subject: [PATCH 1/2] Added in some of the great info about non-homomorphic transformations in type mapping from https://github.com/Microsoft/TypeScript/issues/13224#issuecomment-269807806 --- pages/Advanced Types.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/pages/Advanced Types.md b/pages/Advanced Types.md index 981b900a9..d2a494e8e 100644 --- a/pages/Advanced Types.md +++ b/pages/Advanced Types.md @@ -793,6 +793,29 @@ type PersonPartial = Partial; type ReadonlyPerson = Readonly; ``` +Property mapping is a [homomorphic](https://en.wikipedia.org/wiki/Homomorphism) transformation, so if you wanted to do the + opposite of the `Partial` type and make all optional properties required (a non-homomorphic transformation) you could create + a type `EnsureAll` + +```ts +type EnsureAll = { + [P in K]: T[P]; +} +``` + +And to use it: + +```ts +interface Person { + name: string; + age?: number; +} +type PersonWithAge = EnsureAll // { name: string, age: number } +``` + +Notice the constraint on K is string; this way the type system can not assert that the result of this + transformation is a homomorphic mapping on T, and thus no modifiers are copied through. + Let's take a look at the simplest mapped type and its parts: ```ts From f3168c9bbec4cb225c2549c5ec15f474cde1cb1d Mon Sep 17 00:00:00 2001 From: Jake Ginnivan Date: Sat, 31 Dec 2016 11:21:54 +0800 Subject: [PATCH 2/2] Removed trailing space --- pages/Advanced Types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pages/Advanced Types.md b/pages/Advanced Types.md index d2a494e8e..a57fcff0d 100644 --- a/pages/Advanced Types.md +++ b/pages/Advanced Types.md @@ -794,7 +794,7 @@ type ReadonlyPerson = Readonly; ``` Property mapping is a [homomorphic](https://en.wikipedia.org/wiki/Homomorphism) transformation, so if you wanted to do the - opposite of the `Partial` type and make all optional properties required (a non-homomorphic transformation) you could create + opposite of the `Partial` type and make all optional properties required (a non-homomorphic transformation) you could create a type `EnsureAll` ```ts