Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the return type from a method parameter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’.

>Solution :

You’re pretty close. 2 fixes:

  1. Use T extends instead of T =
  2. Index GameOptions by T
export class MyClass {
  get<T extends keyof GameOptions>(option: T): GameOptions[T] {
    return this.#options[option];
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading