I want to define the type of an object. This can be achieved with a type such as
type objectType = { [key: string]: string };
However, I would like to achieve that the values of the keys are explicitly known without defining the possible keys separately. An example: I define an object as follows. When accessing a non-existent attribute Typescript throws an error.
const value = {
one: "1",
two: 2,
};
console.log(value.three) // Property 'three' does not exist on type '{ one: string; two: string; }'.
But now I want to limit the type of the object values to string and do it like this. Typescript flags the erroneous value, but not the access to a non-existent attribute:
const value: objectType = {
one: "1",
two: 2, // Type error
};
console.log(value.three) // No error
To achieve this, I could define the object type as follows:
type objectType = { [key in "one" | "two"]: string };
However, I would like to avoid the typing as much as possible. With a constantly expanding object this would be a pure copy & past. Is the whole thing more generic possible with a mixture between the first and second example? Only the type of the object values should be specified.
How is this possible? I'm grateful for any help!