Advertisement
Intermediate Angular, TypeScript with Angular

How do you properly type a signal in Angular using TypeScript?

Short answer

TypeScript usually figures out the correct type automatically based on the initial value you give the signal function, but you can also specify the type explicitly inside angle brackets, which is especially useful when the initial value is null but the signal will later hold a…

Save Angular mock interview
Advertisement
AModel answer
TypeScript usually figures out the correct type automatically based on the initial value you give the signal function, but you can also specify the type explicitly inside angle brackets, which is especially useful when the initial value is null but the signal will later hold a specific object type.
// TypeScript infers this is a number automatically
count = signal(0);

// Explicitly typed, useful when starting with null
type User = { name: string; age: number };
user = signal<User | null>(null);
Real-world example
A profile component correctly types its user signal as either a User object or null, letting TypeScript warn the developer immediately if they try to access user's name without first checking that it is not null.
Likely follow-ups
  • Why is it necessary to explicitly type a signal when the initial value is null?
  • How does TypeScript help prevent a common bug where you forget to check if a value is null before using it?
Related topics