Home > Mobile >  Get exact return type from T[keyof T]
Get exact return type from T[keyof T]

Time:07-22

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:

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.

CodePudding user response:

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

CodePudding user response:

You have to specify the specific key of the type T. Not just keyof T.

getPart<TKey extends keyof T>(key: TKey): T[TKey] {
  return this.config[key];
}
  • Related