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 exact return type from T[keyof T]

What I have:

class App<T> {
    config: T // T is supposed to be Record<string, _different types_>
}

config = // T example
{
    'part1': Type1,
    'part2': Type2,
    'part3': Type3
}

What I want to achive:

class App<T> {
    config: T,
    getPart(key) // get part of T with exact type, key is the key of T
}

const data = app.getPart('part2') // returns Type2

What I tried:

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

getPart(key: keyof T): T[keyof T] { // return type becomes T1 | T2 | T3
    return this.config[key];
}

Problem: Is it possible to get the exact return type based?

Thanks.

>Solution :

Is the following behavior what you wanted?

const config = {
    'part1': 3,
    'part2': false,
    'part3': "55"
}

class App<T> {
    config: T
    getPart<U extends keyof T>(key: U): T[U] { 
        return this.config[key];
    }
    constructor(arg0: T) { };
}
let app = new App(config);

const test1 = app.getPart('part1') // type: number
const test2 = app.getPart('part2') // type: boolean
const test3 = app.getPart('part3') // type: string
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