2

I updated my Angular app to v16 and I'm trying to use Signals. Before, I was initializing my variables without initial value

filters: Filter[];

but as I'm using Signals it gives me an error. An argument for 'initialValue' was not provided Is there a way I can create a Signal without initializing its value?

I tried setting its Type to possibly null and giving it null value

signal<Category | null>(null);

But some other errors occurred in the file like Object is possibly 'null'.

And I'm not a fan of using "any" type

So please can you provide another solution?

JSON Derulo
  • 9,780
  • 7
  • 39
  • 56

2 Answers2

3

The signals have been designed with to specifically always have a synchronous value.

This means you have to explicitly create a signal with null or undefined.

For example:

const mySignal = new Signal<{value:number}|null>(null). 

At the moment narrowing isn't working with signals in template. Expect an error when you do {{ mySignal().value }}.

You're going to have to rely on optional chaining operator (.?) : {{ mySignal()?.value }} to prevent that error.

The Angular team is aware of this issue and we can expect some improvements on that !

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
2

How about defining it as a Partial?

signal<Partial<Category >>({});
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 21 '23 at 19:43
  • This is what @Akhil meant: https://www.typescriptlang.org/docs/handbook/utility-types.html – Vaidas D. Aug 07 '23 at 07:38