In some cases, using the optional chaining operator may not be sufficient to narrow down a signal's value type, such as from string | undefined
to string
. To achieve type narrowing, you can use Angular's @if
directive in combination with a getter expression.
By moving the signal to a private property and exposing its value through a public getter property, you can ensure that TypeScript correctly narrows down the type within the @if
block.
This approach guarantees that the same value is used throughout the template, allowing TypeScript to compile the code without errors.
[00:00] Sometimes it will be impossible to use convenient syntax such as the optional chaining operator when we want to narrow down the signal value type. In our case, we wanted to narrow down string or undefined into just a string. In some cases, you'll have to use the angular if statement which will rely on the signal value. [00:20] If we move the piece of the template into the if statement and we remove the optional chaining operator, we will see that type narrowing doesn't work anymore. This is because the item function signal is called twice and there is no way for typescript to guarantee that both of the calls will return the same value type. [00:40] What we can do is we can expose the signal value as if it was a getter, as an expression. So we will move the signal to become a private property and we'll expose the signal as a public property. So what we're going to return here is this dot hashitem [01:01] and we'll make the call. So in this case, we will just move the item like this and since this could be a string or undefined but this is not a function, this appears to be a property, now we can make sure that this is the very same thing and TypeScript compiles it [01:21] correctly as we can see.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!