Signals Data Types
Signals Data Types in Angular
When working with signals, two types of data types are involved:
- Signal data type
- Value stored inside the signal
Both are important and often asked in interviews.
Signal Value Data Type
- A signal stores a value, and that value has its own data type.
- By default, the data type is inferred from the initial value.
- If the signal needs to store multiple data types, you must define it explicitly.
Example
data = signal<string | number | boolean>(null);
- This allows the signal to store string, number, or boolean values.
- If data type is not defined, TypeScript will restrict the value.
Signal Data Type (Writable / Readable)
- Signals themselves also have types.
- Normal signals are WritableSignal.
- Computed signals are read-only Signal.
Writable Signal Example
data: WritableSignal<string> = signal<string>('anil');
- Value can be updated using
set()orupdate().
Computed Signal Example
speed: Signal<number> = computed<number>(() => 90);
- Value cannot be updated directly.
- It depends on other logic or signals.
set() vs update() Method
Signals can be updated using two methods.
set() Method
- Used when the new value does not depend on the previous value.
- Replaces the old value completely.
Example
this.data.set('Sidhu');
update() Method
- Used when the new value depends on the previous value.
- Commonly used with arrays or objects.
Example
this.users.update((item) => [...item, 'bruce']);
- Keeps old values and adds a new one.
- Uses the previous state safely.