Beginner's TypeScript #3

nhannguyendevjs

Nhan Nguyen

Posted on December 20, 2023

Beginner's TypeScript #3

Image description

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;
}
Enter fullscreen mode Exit fullscreen mode

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; }'.
Enter fullscreen mode Exit fullscreen mode

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 }) => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

👉 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:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on December 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner's TypeScript #5
programming Beginner's TypeScript #5

December 22, 2023

Beginner's TypeScript #4
programming Beginner's TypeScript #4

December 21, 2023

Beginner's TypeScript #3
programming Beginner's TypeScript #3

December 20, 2023