My challenge lies in having an object with string keys, but I do not want them to remain as strings. Instead, I desire the keys to be the exact values of the object. This means that I must input the value of the object accordingly to meet certain criteria. Consider the following 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 code snippet, a TypeScript type ObjectType
is crafted whereby the key
is of type string
and the value
is of type ObjectValueType
. My aim is to have the key
match the exact keys present in the Object
(such as camera_stream_endpoint or layout_image). How can I achieve this key inference?
I am hesitant to resort to creating a union type encompassing all the keys within the object due to its extensive nature. Therefore, I would prefer TypeScript to automatically infer these keys from the created object.
One approach I attempted involved utilizing the 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;
This method successfully achieves the desired outcome for the keys. However, it opens up the possibility for arbitrary values to be inserted. For instance, there could be errors in the fields
attribute, which should adhere to the specified type Path<Camera>
. TypeScript will not flag any inconsistencies in this scenario.
Ultimately, my goal is to define both the keys and values of the object. The keys should be inferred from the created variable, while the values will possess their individual type definitions. Is such a feat attainable?