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

How to use value in type syntax

I want return type of my method is one of my class’s properties (dynamically), how can i do this?

Something like this:

interface IObject {
  [key: string]: any
}

class classX<T extends IObject> {
  public methodX(column: keyof T) {
    return (null as any) as T[`${column}`] // T['property']
  }
}
const varX = new classX<{ property: string }>()
varX.methodX('property') // expected type string

const varY = new classX<{ property: number }>()
varY.methodX('property') // expected type number

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

>Solution :

Just add a generic constraint to your method and use that to constrain both your parameter and return type:

interface IObject {
  [key: string]: any
}

class classX<T extends IObject> {
  public methodX<K extends keyof T>(column: K): T[K] {
    return (null as any) as T[K];
  }
}

const varX = new classX<{ property: string }>();
varX.methodX('property');

const varY = new classX<{ property: number }>();
varY.methodX('property');

Playground link

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