Skip to content

Commit cf5882e

Browse files
authored
Add note on unexpected behaviour of Omit with unions
This behaviour is quite unexpected and made me lose many hours before realising it didn't work as I thought. I hope this helps future students. Original code for `UnionOmit` by [Andrii Dieiev](https://github.com/IllusionMH), from: microsoft/TypeScript#39556 (comment)
1 parent 0c516b0 commit cf5882e

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/content/9/en/part9d.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1115,14 +1115,22 @@ interface HealthCheckEntry extends BaseEntry {
11151115
}
11161116
```
11171117
1118-
Now we only need to create the <i>OccupationalHealthCareEntry</i> and <i>HospitalEntry</i> types so we can combine and export them as an Entry type like this:
1118+
Now we only need to create the <i>OccupationalHealthCareEntry</i> and <i>HospitalEntry</i> types so we can combine them in an union and export them as an Entry type like this:
11191119
11201120
```js
11211121
export type Entry =
11221122
| HospitalEntry
11231123
| OccupationalHealthcareEntry
11241124
| HealthCheckEntry;
11251125
```
1126+
An important point concerning unions is that, when you use them with `Omit` to exclude a property, it works in a possibly unexpected way. Suppose we want to remove the `id` from each `Entry`, we could think of using `Omit<Entry, 'id'>`, but [it wouldn't work as we might expect](https://github.com/microsoft/TypeScript/issues/42680). In fact, the resulting type, would only contain the common properties, but not the ones they don't share. A possible workaround is to define a special Omit-like function to deal with such situations:
1127+
1128+
```ts
1129+
// Define special omit for unions
1130+
type UnionOmit<T, K extends string | number | symbol> = T extends unknown ? Omit<T, K> : never;
1131+
// Define Entry without the 'id' property
1132+
type EntryWithoutId = UnionOmit<Entry, 'id'>;
1133+
```
11261134
11271135
</div>
11281136

0 commit comments

Comments
 (0)