I would like to get the of the return type from a method where I pass the key as a parameter and the return is type from the interface.
I looked at this answer Is there a way to "extract" the type of TypeScript interface property? and the way the answers seem to show is when you use a string literal. I however don't know what the string will be passed in as. How can get the type without knowing what the parameter will be?
Here is the closes I have gotten based on the above answer, but it still shows an error
Type 'T' cannot be used to index type 'Partial<GameOptions>'.
interface GameOptions {
production: boolean;
background: string;
stats?: boolean;
objects?: new() => object
}
export class MyClass {
// Set through a method in another class constructor
#options: Partial<GameOptions> = {};
get<T = keyof GameOptions>(option: T): GameOptions[keyof GameOptions] {
return this.#options[option];
}
}
this.#production = this.gameConfig.get('production');
Type 'string | boolean | new() => object | undefined' is not assignable to type 'boolean'.
CodePudding user response:
You're pretty close. 2 fixes:
- Use
T extends
instead ofT =
- Index
GameOptions
byT
export class MyClass {
get<T extends keyof GameOptions>(option: T): GameOptions[T] {
return this.#options[option];
}
}