Example 1:
const myGroup = {
Alice: { age: 5 },
Bob: { age: 6 },
}
function getAge(name: keyof typeof myGroup) {
return myGroup[name].age;
}
getAge('Charlie'); // error: name must be 'Alice' | 'Bob'
↑ This is what I want, however, if I type everything, it'll no longer work:
Example 2
interface People {
age: number;
}
interface PeopleGroup {
[name:string]: People;
}
const myGroup: PeopleGroup = {
Alice: { age: 5 },
Bob: { age: 6 },
}
function getAge(name: keyof typeof myGroup) {
return myGroup[name].age;
}
getAge('Charlie'); // no error, name has type of string
I know I can solve it by using enum or union type, but that requires editing more than one place when adding people. In my real life project, myGroup is a big hard-coded dictionary with complicated structure, and I want to enjoy both typechecking when hard-coding it, and typechecking when querying it. Is there a dry way to do it?