I am new to typescript so this question might be trivial.
Say I defined a type like
type MyType = {
name: string,
age: number,
}
and an object like
const o:MyType = {
name:"John Doe",
age:42
}
I could access the the name via o["name"].
Is it possible instead of using "name" something more safe like o[MyTypeProp.name] where MyTypeProp.name is derived from the actual type and contains every propertyname?
I was looking into MappedTypes and something similar to
type MyTypeProp = {
[Property in keyof MyType]: Property;
};
which gave me not what I was hoping for.
My usecase is to make testing easier: I have a bunch of properties to test whether they are disabled writing this
expect(allDisabled(model, ["isTrackingPresent", "isDistributionPresent", ...]))
is more comfortable than testing each and every manually.
On top getting rid of those "magic strings" would be more comfortable.
>Solution :
It won’t be possible to generate some runtime constants using types, since all types will be gone in runtime. If the variables are correctly typed then there is no need for this kind of object.
It would be possible to generate a type out of the object that would show the structure of the type:
const factory = {
name: {
type: "string",
},
data: {
type: "object",
fields: {
age: {
type: "number"
}
}
}
} as const
Then have a type for converting "string", "number" to actual type:
type TypeMap = {
string: string;
number: number;
}
And using some mapped type you could recursively go through the factory and generate a type.