Can deepComputed
signals work with unknown key names?
#4945
-
I am a bit confused on how ExampleSay I have this interface Student {
id: string;
name: string;
grade: string;
}
interface State {
students: {
[id: string]: Student;
};
}
const INITIAL_STATE = {
students: {},
} as const satisfies State;
/**
* Example Signal store for a school.
*/
export const SchoolStore = signalStore(
{providedIn: 'root'},
withState<State>(INITIAL_STATE),
withComputed((store) => ({
// Object is grouped together by unknown keys
studentsByGrade: deepComputed<Readonly<Record<string, readonly Student[]>>>(
() =>
Object.values(store.students()).reduce<Record<string, Student[]>>(
(acc, student) => {
const grade = student.grade;
acc[grade] ??= [];
acc[grade].push(student);
return acc;
},
{},
),
),
})),
withMethods((store) => ({
addStudent(student: Student) {
patchState(store, (state) => ({
students: {...state.students, [student.id]: student},
}));
},
getStudentsByGrade(grade: string) {
return computed<readonly Student[]>(
() => store.studentsByGrade[grade]?.() ?? [], // Typescript error here.
);
},
})),
); The error I get during compilation is that:
It seems like the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Signals are created lazily for known keys only, meaning they’re only wrapped as signals once they're accessed and confirmed to exist. If you want every possible property — even undefined or unknown ones — to behave like a signal from the start, you'd need to fundamentally change how |
Beta Was this translation helpful? Give feedback.
Signals are created lazily for known keys only, meaning they’re only wrapped as signals once they're accessed and confirmed to exist. If you want every possible property — even undefined or unknown ones — to behave like a signal from the start, you'd need to fundamentally change how
toDeepSignal
works. That would involve returning a signal for every property access, regardless of whether the key exists in the object at that moment. This improves ergonomics but comes with trade-offs in type safety, performance, and runtime guarantees.