basically speaking i have two interfaces:
interface config {
lang: "en" | "de";
test: number;
}
interface Accessor {
key ( k: keyof config ): config[k];
}
and i want to dynamically have the type of whatever i access from the config type, via the Accessor object. is that possible?
note: my code is a lot more complicated and i cannot just access the keys directly, but it boils down to this in the end
CodePudding user response:
The key() method signature in your Accessor interface should return an indexed access type of the form Config[X] where X is the type of the k parameter. Your attempt, Config[k], is not valid, because k is the value of the parameter; you need its type. This can be remedied using the typeof type operator like so:
interface Accessor {
key(k: keyof Config): Config[typeof k];
}
This now compiles with no error. And you can even use it:
declare const a: Accessor;
const langProp = a.key("lang");
// const langProp: number | "en" | "de" 