Denote an Optional Property
This is a one character solution.
Adding a ?
before the colon tells TypeScript that the property isn't required in order for the function to work.
With this update, we don't have to pass in a last
if we don't want to:
export const getName = (params: { first: string; last?: string }) => {
Adding ?
will also work when using named types, or anywhere else object keys can be specified.
type 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.
If you have prior experience with TypeScript, you might have seen a type explicitly set to string
or undefined
as seen below:
type Params = { first: string; last: string | undefined }
However, written this way we do have to pass last
. More on "or" later.
If you want to set a property as optional, use the ?
.
Transcript
The trick here is to add this little character just before the colon. When I remove it, we go back to basically the problem set-up. What this does is it means that you do not need to pass this in order for this to work.
I can extract this to a type if I want to. Type params equals this, and it will work in there too. Anywhere that you can specify an object key, you can use this. It means that I can pass this last if I want to.
You notice that, without this, if I remove it again and I go on the autocomplete, there's no question mark after that last just there. Whereas, if I add that, then I get the question mark saying I could pass either a string or undefined. That little or will come up later, but it's a nice way of saying it.
An alternative, if you've got a little bit of experience with TypeScript, is you could do last or undefined here, but this means you do need to pass in something in there. I could say last is undefined, and that would make it happy, but adding that little question mark character means that I don't even need to pass the property.