How can I set the key of a function returned object to the value of it's parameter?
I have the following:
const makeCache = <A, T extends string>(name: T, base = {}) => {
const cache = base;
return {
[name]: cache,
} as {
[key in keyof T]: typeof cache; // this didn't work
// [key in typeof name]: typeof cache; // this didn't work
// [key in keyof typeof name]: typeof cache; // this didn't work
// [key: typeof name]: typeof cache; // this didn't work
};
};
I'm trying to make an autocomplete with the value returned as key:
makeCache('root').root // ok
makeCache('hello').hello // ok
makecache('error').notError // error!
I've done before, I just don't remember how.
CodePudding user response:
This seems to do the trick:
const makeCache = <A, T extends string>(name: T, base = {}) => {
const cache = base;
return {
[name]: cache,
} as {
[key in typeof name]: typeof cache
};
};
makeCache('error').error // bombs with notError