Skip to content

Commit a02ef70

Browse files
committed
Added in some of the great info about non-homomorphic transformations in type mapping from microsoft/TypeScript#13224 (comment)
1 parent 4fd22be commit a02ef70

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

pages/Advanced Types.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,29 @@ type PersonPartial = Partial<Person>;
793793
type ReadonlyPerson = Readonly<Person>;
794794
```
795795

796+
Property mapping is a [homomorphic](https://en.wikipedia.org/wiki/Homomorphism) transformation, so if you wanted to do the
797+
opposite of the `Partial` type and make all optional properties required (a non-homomorphic transformation) you could create
798+
a type `EnsureAll`
799+
800+
```ts
801+
type EnsureAll<T, K extends string> = {
802+
[P in K]: T[P];
803+
}
804+
```
805+
806+
And to use it:
807+
808+
```ts
809+
interface Person {
810+
name: string;
811+
age?: number;
812+
}
813+
type PersonWithAge = EnsureAll<Person, keyof Person> // { name: string, age: number }
814+
```
815+
816+
Notice the constraint on K is string; this way the type system can not assert that the result of this
817+
transformation is a homomorphic mapping on T, and thus no modifiers are copied through.
818+
796819
Let's take a look at the simplest mapped type and its parts:
797820
798821
```ts

0 commit comments

Comments
 (0)