You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Which @angular/* package(s) are the source of the bug?
core, Don't known / other
Is this a regression?
No
Description
The current implementation of signals uses a function to access the value, and TypeScript has issues with type guards in that case:
constcount=signal(nullasnull|number);consttotal: number=count()!==null ? count() : 0;// Error: Type `number | null` is not assignable to type `number`
This can be workaround by storing the value in a temporary variable or with an explicit cast, but this could be a bit cumbersome, as I imagine the same would happen with ngIf in templates:
constcount=signal(nullasnull|number);constvalue=count();consttotal: number=value!==null ? value : 0;// Works
Please provide a link to a minimal reproduction of the bug
No response
Please provide the exception or error you saw
No response
Please provide the environment you discovered this bug in (run ng version)
No response
Anything else?
No response
Reacted by Vinit Neogi, Enea Jahollari, Toni Villena, Harpush, hyperlife1119, enea4science, Wolf Walter, Mateusz Turcza, Misha Hrokhola, David Lejeune and 147 more
Side note: this is not a big deal, the issue is just to trace a discussion we had with @pkozlowski-opensource on Slack
Reacted by Pawel Kozlowski
Reacted by montella1507, Mateusz Turcza, Juliano, Alex Hauck, jsprw, Christopher Pierce, Mickaël Olaria, Liam Morrow, César Alberca, Tim Underhay and 48 more
<span*ngIf="shape().kind === ''Circle">
This is a circle with r={{shape().r}} //type error
</span>
You would need to do
<ng-container*ngIf="shape() as shape"> //ngIf hack as with | await
<span*ngIf="shape.kind === 'Circle'">
This is a circle with r={{shape.r}} //now ok
</span></ng-container>
The same can be used for null | undefined as long as we are not expecting any of '', 0, false so null | undefined is bigger problem as no full workaround for it
<ng-container*ngIf="shapeOrNull() as shape"> //ngIf hack as with | await
<span*ngIf="shape">
This is a circle with r={{shape.r}} //now ok
</span></ng-container>
<span*ngIf="numberOrNull() as num"> //will not show answer work for 0
This number is {{num}}
</span>
Reacted by Mateusz Turcza, Misha Hrokhola, Clara Castillo, Torsten Severing, Maksim Popov, Juliano, Mickaël Olaria, Salem Ouerdani, Sebastian Podgajny, stefnotch and 18 more
It all boils down to how deep signals should go... Theoretically you could create a computed called circleShapeRadius but I am not sure about it. It is also the point of maybe nested signals are needed?
One more option is ngIf would produce a casted signal with as.
For example a new directive (Maybe it can be done inline in template?):
<div*ngSignalIf="let circleShapeSignal when shapeSignal match checkFn">
Radius is: {{circleShapeSignal().radius}}
</div>
functioncheckFn(shape: Shape): shape is CircleShape{returnshape.kind==='circle';}
And simplified code to how it works:
typeShape=|{type: 'circle';radius: number}|{type: 'rectangle';size: number};constshapeSignal=signal<Shape>({type: 'circle',radius: 10});functiontest<T,KextendsT>(signal: Signal<T>,checkFn: (value: T)=>value is K){constcastedSignal=computed(()=>{constvalue=signal();returncheckFn(value) ? value : undefined;});effect(()=>{constcasted=castedSignal();if(casted){renderView(castedSignal);// pass context to template}else{destroyView();}});}
Reacted by montella1507, Jason Kossis, Mateusz Turcza, Juliano, Alex Hauck, medonat, Sergej Sintschilin, Tim Underhay, Isaac Aggrey, RobertasM and 22 more
Seems like Angular with their new control flow wanted to get closer to JS syntax.
In this light the only way to extract a value from signals, observables and promises being checking against all falsy values is really ugly, not very JS syntax -y and can also be quite limiting (for instance if we have a signal that can be null, undefined, string, but we only want to check if it's not undefined, we can't, instead it won't even pass for "" empty string, this is unacceptable and ridiculous TBH).
It makes no sense to loop over null, undefined, document.all and call it "empty" or not err when trying to loop over 0, -0, 0n, false, NaN. The only thing that should be called "empty" is a JS array with length of 0.
I think this is a place where being explicit rather than implicit is the right way. And for that the syntax I'm proposing would be very helpful.
@using (val() as val) {
<p>{{ val }}</p>
}
// could also have it potentially apply to any logic block that immediately follows it
@using (val() as val)
@if (val === null) {
...
} @else if (val === undefined) {
...
} @else {
@for (valElement of val; track valElement.id) {
...
} @empty {
...
}
}
// could also drop `as` keyword, and infer the name from the signal name
// so we don't have to keep track of yet another variable name
@using (val()) {
<p>{{ val }}</p>
}
It would also be very helpful to implement, through a flag, strict syntax rules for @for and whatever else needs it, so the above c**p doesn't pass anymore.
Reacted by Samuel Fernández, Serhii Shvets, Juan González, Aleksandr Plokhikh and Magnus Wolffelt
Currently this is not allowed because error might be null. Of course I could do error(?/!).message but I'm wondering if there is another way. Is the only other alternative currently:
I have an issue, I need to set the value of the signal in the AfterViewInit because I need the component to be ready, after I check if the values is not undefined, it keeps saying it may be undefined.
@alxhub could you use a similar solution to ResourceRef.hasValue() for Signals directly? E.g. with a new method Signal.isPresent(): this is Signal<Exclude<T, undefined | null>>.
If you want updates too then add a setter for WritableSignals:
set(val) { this.set(val); }
Some caveats:
My typescript is not good enough to add a single declaration for all signals. I tried function addValueAccessor<T, S extends Signal<T>>(sig: S): S & { value: T } but it loses the value of T. I just overloaded it for all the signals I wanted.
Cannot be used directly on InputSignal because of the compiler's static type checking: TS-998110: Unsupported call to the input function....
Activity
cexbrayat commentedon Feb 22, 2023
Side note: this is not a big deal, the issue is just to trace a discussion we had with @pkozlowski-opensource on Slack
kbrilla commentedon Feb 22, 2023
Won’t this work:
or maybe add mapper
but this would not work well in templates as there is no support for arrow functions there
JeanMeche commentedon Feb 22, 2023
The issue is more about narrowing. In a template with
That wouldn't happen if the value wasn't acced via a function !
kbrilla commentedon Mar 7, 2023
Well there is not only a nullability problem but any kind of type guard
You would need to do
The same can be used for null | undefined as long as we are not expecting any of '', 0, false so null | undefined is bigger problem as no full workaround for it
Harpush commentedon Mar 14, 2023
It all boils down to how deep signals should go... Theoretically you could create a computed called
circleShapeRadiusbut I am not sure about it. It is also the point of maybe nested signals are needed?One more option is
ngIfwould produce a casted signal withas.For example a new directive (Maybe it can be done inline in template?):
And simplified code to how it works:
ArielGueta commentedon Oct 24, 2023
Any solution for now? this is a big issue
flevi29 commentedon Nov 7, 2023
Seems like Angular with their new control flow wanted to get closer to JS syntax.
null,undefined,string, but we only want to check if it's notundefined, we can't, instead it won't even pass for""empty string, this is unacceptable and ridiculous TBH).null,undefined,document.alland call it "empty" or not err when trying to loop over0,-0,0n,false,NaN. The only thing that should be called "empty" is a JS array withlengthof 0.I think this is a place where being explicit rather than implicit is the right way. And for that the syntax I'm proposing would be very helpful.
It would also be very helpful to implement, through a flag, strict syntax rules for
@forand whatever else needs it, so the above c**p doesn't pass anymore.montella1507 commentedon Nov 13, 2023
it is big deal. It is really HARD to use for real-world projects.
JesseZomer commentedon Dec 29, 2023
Lets say I have the following template: (query is either a succesfull response or an error response type with an error field)
@switch (query().status) { @case ('pending') { <span>...loading</span> } @case ('error') { <span>Error: {{ query().error.message }}</span> } }Currently this is not allowed because error might be null. Of course I could do error(?/!).message but I'm wondering if there is another way. Is the only other alternative currently:
@if (query(); as query) { @switch (query.status) { @case ('pending') { <span>query.status</span> } @case ('error') { <span>Error: {{ query.error.message }}</span> } } }?
something like
@switch ((query() as query).status) { @case ('pending') { <span>...loading</span> } @case ('error') { <span>Error: {{ query.error.message }}</span> } }would be nice
27 remaining items
JeanMeche commentedon Apr 25, 2024
@c-harding, this issue is being investigated, please have a look at #55456
c-harding commentedon Apr 25, 2024
@JeanMeche that PR is only for templates rather than in TypeScript
Eduard20CR commentedon May 31, 2024
I have an issue, I need to set the value of the signal in the AfterViewInit because I need the component to be ready, after I check if the values is not undefined, it keeps saying it may be undefined.
I fixed it by putting stage in a local variable, but I dont think it is a great solution, am I doing something wrong?
amakhrov commentedon Nov 20, 2024
Is the official recommendation now - using
@let(as per this comment)?If so, should we now close this issue? Or is there anything else that the team is thinking of to further improve it?
reduckted commentedon Nov 20, 2024
Using
@letwould only help in templates. It doesn't solve the problem in TypeScript.#49161 (comment)
resourceandrxResource'svalue()causes compliation error with strict checks #59530 as a duplicate of this issuec-harding commentedon Jan 31, 2025
@alxhub could you use a similar solution to ResourceRef.hasValue() for Signals directly? E.g. with a new method
Signal.isPresent(): this is Signal<Exclude<T, undefined | null>>.JeanMeche commentedon Jan 31, 2025
Ideally this should be fixed by a language feature, this is currently being discussed here microsoft/TypeScript#60948
baarney commentedon Jun 10, 2025
In a similar vein to #49161 (comment), for those that don't mind using a value accessor you can just add it directly to the signal:
Usage:
If you want updates too then add a setter for
WritableSignals:Some caveats:
function addValueAccessor<T, S extends Signal<T>>(sig: S): S & { value: T }but it loses the value ofT. I just overloaded it for all the signals I wanted.InputSignalbecause of the compiler's static type checking:TS-998110: Unsupported call to the input function....refactor: remove nullability from signals to ensure type safety
Feat/apiv3 pagination (#1423)