I am completely new to Typescript and I am fascinated by the way it can check types.
One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are declared in the same object?
Let me provide an example to better explain my question. Here are some object and type definitions:
type ElemField = { name: string }
type Elem = Record<string, ElemField>
type Relation = { path: string[] }
type MySchema = {
elem: Record<string, Elem>,
relations: Record<string, Relation>
}
const test: MySchema = {
elem: {
elem1: {
prop1: { name: 'string' },
},
elem2: {
prop2: { name: 'string' },
prop3: { name: 'string' },
},
elem3: {
prop4: { name: 'string' },
}
},
relations: {
relation1: {
path: ['elem2', 'elem1'],
},
relation2: {
path: ['elem3', 'elem1'],
}
}
}
I am curious to know if it is feasible to validate at compile time whether the path
array only includes values that match keys from the root level elements
object.
I am unsure if features like keyof
, generics, or other advanced Typescript functionality can help achieve this kind of validation.
EDIT: A big thank you to Shahriar Shojib
for providing a helpful solution. However, I still wonder if there is a way to accomplish this without using a function, but rather by strictly specifying the object's type.