Is there a method to ensure that code like this can compile while maintaining type safety?
type ComplexObject = {
primitive1: boolean;
complex: {
primitive2: string;
primitive3: boolean;
}
};
interface MyReference {
myKey: keyof ComplexObject;
}
const works1: MyReference = {
myKey: "primitive1"
}
const works2: MyReference = {
myKey: "complex"
}
const iWantThisToCompile1: MyReference = {
myKey: "complex.primitive2" // Error: Type '"complex.primitive2"' is not assignable to type '"primitive1" | "complex"'.
}
const iWantThisToCompile2: MyReference = {
myKey: "complex['primitive3']" // Error: Type '"complex['primitive3']"' is not assignable to type '"primitive1" | "complex"'.
}
// const iDontWantThisToCompile1: MyReference = {
// myKey: "primitive2"
// }
// const iDontWantThisToCompile2: MyReference = {
// myKey: "primitive3"
// }
You can experiment with this snippet here.