Beginner's TypeScript #3
Nhan Nguyen
Posted on December 20, 2023
⭐ Set Properties as Optional ⭐
Consider this getName function:
export const getName = (params: { first: string; last: string }) => {
if (params.last) {
return `${params.first} ${params.last}`;
}
return params.first;
}
We can see that we do not need to pass in a last name for the function to work.
However, TypeScript does not know that yet.
We have an error:
Argument of type '{ first: string; }' is not assignable to parameter of type '{ first: string; last: string; }'.
Property 'last' is missing in type '{ first: string; }' but required in type '{ first: string; last: string; }'.
We will figure out how to type the object so that last is optional.
👉 Solution:
This is a one-character solution.
Adding a ? before the colon tells TypeScript that the property is not required in order for the function to work.
With this update, we do not have to pass in a last if we don't want to:
export const getName = (params: { first: string; last?: string }) => {
// ...
}
Tooling in VS Code is smart enough to recognize if a key is optional. This can be seen in the autocomplete, where you will be reminded that last should be either a string or undefined.
type Params = { first: string; last: string | undefined }
👉 Summary:
If you want to set a property as optional, use the❓.
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Posted on December 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.