I have an object with string as keys. But, I don’t want it to be string. I want the key strings to be that exact value of the object. I have to type the value of that object as well to follow certain rules. Here is an example,
type ObjectValueType = {
checked: boolean;
fields: Path<Camera>[];
};
type ObjectType = Record<string, ObjectValueType>;
const Object: ObjectType = {
camera_stream_endpoint: {
checked: false,
fields: ['camera_stream_endpoint'],
},
layout_image: {
checked: false,
fields: ['layout_image'],
},
};
In the above object, I have created a typescript type ObjectType
which has string
as key
and ObjectValueType
as value
. I don’t want key
to be string
. I want the key
to be the exact keys of the Object
(camera_stream_endpoint or layout_image or rest). How do I infer this key
?
I don’t want to create a union type of the object key because that object is an extremely long object with a lot of keys. So, I would prefer TypeScript infer that key from the created object.
One thing I tried is using assertion as const
like so
const Object = {
camera_stream_endpoint: {
checked: false,
fields: ['camera_stream_endpoint'],
},
layout_image: {
checked: false,
fields: ['layout_image'],
},
} as const;
The above achieves the desired outcome for the keys. But, now, I can put whatever I want for the value
. Example, I could easily mess up the fields
which should follow the defined type Path<Camera>
. TypeScript won’t complain at all for the wrong values.
I want to type the keys and values of the object. Keys should be inferred from the created variable and value will have its own type definition. Is it possible?