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
>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');