Skip to content

Commit

Permalink
Create ts-exact-optional-property-types.md
Browse files Browse the repository at this point in the history
  • Loading branch information
petermekhaeil authored Jan 1, 2024
1 parent e2f670a commit bf9ff68
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions learnings/ts-exact-optional-property-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# TypeScript: exactOptionalPropertyTypes

TypeScript handles optional and undefined differently - [exactOptionalPropertyTypes](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes) will help catch scenarios where `undefined` should be typed explicitly.

When turned off:

```ts
type User = {
email?: string;
}

const user: User = { email: undefined }
// Valid
```

When turned on:

```ts
type User = {
email?: string;
}

const user: User = { email: undefined }
// Type '{ email: undefined; }' is not assignable to type 'User' with 'exactOptionalPropertyTypes: true'.
// Consider adding 'undefined' to the types of the target's properties.
```

Read [optional vs undefined | TkDodo's blog](https://tkdodo.eu/blog/optional-vs-undefined) to learn the difference and how this can help.

0 comments on commit bf9ff68

Please sign in to comment.