Consider a scenario where you have the following type definition:
type MyType = {
A: number | string
}
If you try to assign a value like this, TypeScript will correctly flag it as an error:
const myValue1: MyType = {
A: 123,
B: "Oh!", // This will raise a type error since property B was mistakenly defined
}
Alternatively, if you define a variable without explicitly specifying its type, you can extract the type of the object literal in this way:
const myValue2 = {
A: 123
}
const MyLiteralType = typeof myValue2; // Result: {A: number}
Ideally, you might want both scenarios:
- To enforce strict checking when assigning values to variables (disallowing additional properties), and
- To automatically extract the type of the object literal.
Is there a clever way to achieve this in TypeScript without having to redundantly define a second type ({A: number})? Any suggestions are welcome!
It appears that TypeScript currently only supports one of these features at a time:
- You can either get strict type checking by assigning an object literal to a typed variable, or
- You can extract the type of the object literal but sacrifice strict type enforcement.
Perhaps there's a workaround using template tricks to compare the types (MyType and MyLiteralType) and throw an error if extra properties are detected?