Skip to content

signals: TypeScript and nullability #49161

Open

Description

@cexbrayat

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:

const count = signal(null as null | number);
const total: 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:

const count = signal(null as null | number);
const value = count();
const total: 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

Activity

  1. cexbrayat commented on Feb 22, 2023

    @cexbrayat
    MemberAuthor

    Side note: this is not a big deal, the issue is just to trace a discussion we had with @pkozlowski-opensource on Slack

  2. added
    area: core
    core: reactivity
    on Feb 22, 2023
  3. modified the milestone: needsTriage on Feb 22, 2023
  4. kbrilla commented on Feb 22, 2023

    @kbrilla
    Contributor

    Won’t this work:

    const count = signal(null as null | number);
    const total: number = count() ?? 0;

    or maybe add mapper

    count((val)=> val !== null ? val : 0)

    but this would not work well in templates as there is no support for arrow functions there

  5. JeanMeche commented on Feb 22, 2023

    @JeanMeche
    Member

    The issue is more about narrowing. In a template with

    // count still number | null.

    That wouldn't happen if the value wasn't acced via a function !

  6. kbrilla commented on Mar 7, 2023

    @kbrilla
    Contributor

    Well there is not only a nullability problem but any kind of type guard

    type Shape = {kind: 'Circle', r: number} | {kind: 'Square': a: number};
    shape= Signal<>;
    <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 >
  7. Harpush commented on Mar 14, 2023

    @Harpush

    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>
    function checkFn(shape: Shape): shape is CircleShape {
      return shape.kind === 'circle';
    }

    And simplified code to how it works:

    type Shape =
      | { type: 'circle'; radius: number }
      | { type: 'rectangle'; size: number };
    const shapeSignal = signal<Shape>({ type: 'circle', radius: 10 });
    
    function test<T, K extends T>(
      signal: Signal<T>,
      checkFn: (value: T) => value is K
    ) {
      const castedSignal = computed(() => {
        const value = signal();
        return checkFn(value) ? value : undefined;
      });
    
      effect(() => {
        const casted = castedSignal();
    
        if (casted) {
          renderView(castedSignal); // pass context to template
        } else {
          destroyView();
        }
      });
    }
  8. ArielGueta commented on Oct 24, 2023

    @ArielGueta

    Any solution for now? this is a big issue

  9. flevi29 commented on Nov 7, 2023

    @flevi29

    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.

  10. montella1507 commented on Nov 13, 2023

    @montella1507

    Side note: this is not a big deal, the issue is just to trace a discussion we had with @pkozlowski-opensource on Slack

    it is big deal. It is really HARD to use for real-world projects.

  11. JesseZomer commented on Dec 29, 2023

    @JesseZomer
    Contributor

    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

  12. 27 remaining items

  13. JeanMeche commented on Apr 25, 2024

    @JeanMeche
    Member

    @c-harding, this issue is being investigated, please have a look at #55456

  14. c-harding commented on Apr 25, 2024

    @c-harding

    @JeanMeche that PR is only for templates rather than in TypeScript

  15. Eduard20CR commented on May 31, 2024

    @Eduard20CR

    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.

      stage: WritableSignal<Konva.Stage | undefined> = signal(undefined);
    
      ngAfterViewInit(): void {
        this.initStage()
      }
    
      initStage() {
        const width = this.container.nativeElement.offsetWidth;
        const height = this.container.nativeElement.offsetHeight;
    
        this.stage.set(new Konva.Stage({
          container: 'container',
          width,
          height,
          scale: { x: this.getScale(), y: this.getScale() },
        }))
    
        if (!this.stage()) return;  // -> 'stage' is possibly 'undefined'.
    
        stage.on('click', (e) => {
          this.transformer().nodes([]);
          if (e.target === this.stage()) return;
          if (e.target instanceof Konva.Image) return;
          this.transformer().nodes([e.target]);
        })
    }

    I fixed it by putting stage in a local variable, but I dont think it is a great solution, am I doing something wrong?

      stage: WritableSignal<Konva.Stage | undefined> = signal(undefined);
    
      ngAfterViewInit(): void {
        this.initStage()
      }
    
      initStage() {
          const width = this.container.nativeElement.offsetWidth;
        const height = this.container.nativeElement.offsetHeight;
    
        this.stage.set(new Konva.Stage({
          container: 'container',
          width,
          height,
          scale: { x: this.getScale(), y: this.getScale() },
        }))
    
        const stage = this.stage()
        if (!stage) return;
    
        stage.on('click', (e) => {
          this.transformer().nodes([]);
          if (e.target === this.stage()) return;
          if (e.target instanceof Konva.Image) return;
          this.transformer().nodes([e.target]);
        })
    }
  16. amakhrov commented on Nov 20, 2024

    @amakhrov

    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?

  17. reduckted commented on Nov 20, 2024

    @reduckted

    Using @let would only help in templates. It doesn't solve the problem in TypeScript.

    #49161 (comment)

  18. c-harding commented on Jan 31, 2025

    @c-harding

    @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>>.

  19. JeanMeche commented on Jan 31, 2025

    @JeanMeche
    Member

    Ideally this should be fixed by a language feature, this is currently being discussed here microsoft/TypeScript#60948

  20. baarney commented on Jun 10, 2025

    @baarney

    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:

    export function addValueAccessor<T>(sig: Signal<T>) {
      return Object.defineProperty(sig, 'value', {
        get() { return this(); }
      }) as Signal<T> & { value: T };
    }
    

    Usage:

    type Foo = {
      name: string;
    }
    
    const f1 = signal<Foo | undefined>(undefined);
    const f1Name = f1() ? f1().name : "unknown";                // Object is possibly undefined
    
    const f2 = addValueAccessor(signal<Foo | undefined>(undefined));
    const f2Name = f2.value ? f2.value.name : "unknown";        // correctly narrowed
    

    If you want updates too then add a setter for WritableSignals:

        set(val) { this.set(val); }
    

    Some caveats:

    1. 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.
    2. Cannot be used directly on InputSignal because of the compiler's static type checking: TS-998110: Unsupported call to the input function....
  21. added a commit that references this issue on Jul 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: corecore: reactivitycross-cutting: signalscross-cutting: types

Type

No type

Projects

  • Status
    In Progress

Relationships

None yet

Development

No branches or pull requests

Issue actions