To utilize normalized data effectively, I have created an object with keys that can only be a list of numbers within a specified array. Is there a way to enforce this restriction in typing so that if I attempt to access the object using a non-array key, an error is triggered (rather than just the possibility of encountering an undefined value)?
In simpler terms, consider an object of type Foo:
const x:Foo = {
allIds: [1,3],
structured: {
1: "foo",
3: "bar"
}
}
Is it feasible to define Foo in a manner such that the following operation results in an error due to '2' not being present in the allIds array?
const z = x.structured[2]
I've attempted the following approach, but it seems ineffective as the index signature expands to "number":
interface Foo {
allIds: number[]
structured: Record<Foo["allIds"][number],string>
}
Any assistance on this matter would be greatly appreciated.
Please note: The values within allIds are statically defined in the code and do not change at runtime.