typescript: whats the actual difference between `name?: string` and `name: string | undefined`?
Kevin Tran@kevtran_dev
my senior left a review comment "these are not the same thing" on this:
type User = {
name?: string
}
type User2 = {
name: string | undefined
}
in my head both mean "name might be undefined". when i hover in vscode they look almost the same. whats the real difference and when would i pick one over the other? i googled and found something about exactOptionalPropertyTypes and now im more confused lol
Accepted answer
The difference is whether the key has to exist.
With name?: string you can leave it out entirely: const u: User = {} is fine.
With name: string | undefined the key is required, you just may set it to undefined: const u: User2 = {} is an error, you need { name: undefined }.
When it matters: required-but-maybe-undefined forces every caller to think about it, which is great for options where forgetting is a bug. Optional is better for stuff that is genuinely optional.
exactOptionalPropertyTypes makes name?: string stricter: it then means "absent, or a string", and you can NOT explicitly write { name: undefined }. Most projects dont turn it on, so dont worry about that one yet.
Written by
Kevin Tran
used to run a pho kitchen, now junior frontend dev in houston (8 months in!!). learning react, typescript and how to not panic in standups. ask me about broth
Get the best of #types-go-brr weekly
One email each Monday with the most useful posts. No spam; unsubscribe in one click.
Comments
Sign in to join the conversation.
Sign in to commentAccepted answer
Siobhan O'Rourke@siobhan_tests
The difference is whether the key has to exist.
With name?: string you can leave it out entirely: const u: User = {} is fine.
With name: string | undefined the key is required, you just may set it to undefined: const u: User2 = {} is an error, you need { name: undefined }.
When it matters: required-but-maybe-undefined forces every caller to think about it, which is great for options where forgetting is a bug. Optional is better for stuff that is genuinely optional.
exactOptionalPropertyTypes makes name?: string stricter: it then means "absent, or a string", and you can NOT explicitly write { name: undefined }. Most projects dont turn it on, so dont worry about that one yet.
Kevin Tran@kevtran_dev
ohhh the key has to EXIST. that makes so much sense now. thank you!! going to reply to my senior like i knew it all along