Learn to avoid type bugs in TypeScript by understanding when to use foo?: string vs foo: string | undefined. Clear examples & best practices.
Duration
2 min
Access
Free
Transcript
Available
Learn to avoid type bugs in TypeScript by understanding when to use foo?: string vs foo: string | undefined. Clear examples & best practices.
Duration
2 min
Access
Free
Transcript
Available
Video Transcript
Here is a subtle but important difference in TypeScript that cause a lot of confusion. Optional key versus optional value. These two types look similar, but they behave differently. This one with the question mark means the key foo might not exist at all. But this one with the string or undefined definition means the key will exist, but its value might be undefined.
Let's see an example. Let's create an object of optional key and pass no value to there. With optional key we can omit the key entirely. Now, let's create another object, type optional value, and do the same without any key. Now, there is an error.
TypeScript expects the property foo to be defined because it's required by the optional value. Another example is when we use the in check. Let's create a function as an object with optional key and let's create an if statement. Check if the foo property is present in the object and let's just console.log. If we use the in check here with the optional key we are verifying the key exists before using.
If we use the optional value here we can remove the if statement because the key will always exist. Might be undefined but will exist. So as a summary use this one full question mark when the key might not exist. For example, optional prop in a component in your react application or some optional property in your API or the arguments of a function. Use this one with optional value when the key is always present but could be uncertain like could be a string or might be not just not be defined like an empty string.
Understanding this distinction that these two definitions are not interchangeable will make your TypeScript models more accurate and reliable.