I have declared an object like so:
const example = {
morning: (name) => `Good morning ${name}!`,
evening: (name) => `Good evening ${name}!`
}
In its raw form, the object has strongly typed keys (I can access them using dot notation), but the values could be anything. That's why I decided to introduce a type signature:
const example: {
[K: string]: (name: string) => string;
} = {
morning: (name) => `Good morning ${name}!`,
evening: (name) => `Good evening ${name}!`
}
Now my object values are strongly typed, but the keys aren't, and I could try to access any key using dot notation without TypeScript complaining (for example, I could write console.log(example.doesntexist)
, and I wouldn't get editor autocompletion for the object keys either). So I tried this:
const example: {
[K in keyof typeof example]: (name: string) => string;
} = {
morning: (name) => `Good morning ${name}!`,
evening: (name) => `Good evening ${name}!`
}
Now I'm getting a circular constraint error (Type parameter 'K' has a circular constraint
and 'example' is referenced directly or indirectly in its own type annotation
). I'm aware I could do something like this
const example: {
[K in 'morning' | 'evening']: (name: string) => string;
} = {
morning: (name) => `Good morning ${name}!`,
evening: (name) => `Good evening ${name}!`
}
but that's redundant (and I hate redundancy/code duplication). Is there a way to do what I want to?