Signals Data Types

Signals Data Types in Angular

When working with signals, two types of data types are involved:

  1. Signal data type
  2. Value stored inside the signal

Both are important and often asked in interviews.


Signal Value Data Type

  1. A signal stores a value, and that value has its own data type.
  2. By default, the data type is inferred from the initial value.
  3. If the signal needs to store multiple data types, you must define it explicitly.

Example

data = signal<string | number | boolean>(null);
  1. This allows the signal to store string, number, or boolean values.
  2. If data type is not defined, TypeScript will restrict the value.


Signal Data Type (Writable / Readable)

  1. Signals themselves also have types.
  2. Normal signals are WritableSignal.
  3. Computed signals are read-only Signal.


Writable Signal Example

data: WritableSignal<string> = signal<string>('anil');
  1. Value can be updated using set() or update().


Computed Signal Example

speed: Signal<number> = computed<number>(() => 90);
  1. Value cannot be updated directly.
  2. It depends on other logic or signals.


set() vs update() Method

Signals can be updated using two methods.

set() Method

  1. Used when the new value does not depend on the previous value.
  2. Replaces the old value completely.


Example

this.data.set('Sidhu');

update() Method

  1. Used when the new value depends on the previous value.
  2. Commonly used with arrays or objects.


Example

this.users.update((item) => [...item, 'bruce']);
  1. Keeps old values and adds a new one.
  2. Uses the previous state safely.