0

I have two types of config one for auth and one for general config which doesn't have any secret variables I used to have two functions but now I'm trying to have only one function but I wasn't able to implement this code with errors, I couldn't find what I'm doing wrong

interface config {
    config: string;
    config_example: string;
} 

interface auth {
    auth: string;
    auth_example: string;
}

type configType = "auth" | "config";
type getType<C extends configType> = C extends "auth" ? keyof auth : C extends "config" ? keyof config : never;

const auth: auth = {
    auth: '',
    auth_example: ''
}

const config: config = {
    config: '',
    config_example: ''
}

function getConfig<
    C extends configType,
    K extends keyof getType<C>
>(config: C, key: K): getType<C>[K] {
    switch (config) {
        case "auth":
            return auth[key];
        case "config":
            return config[key];
        default:
            throw new Error();
    }
} 

here's the typescipt playground code of this

If I put //@ts-ignore to the errors, the IDE correctly determines the types and everything but I don't want to implement this with //@ts-ignore I don't even know if this is possible to do that but any ideas?

1 Answer 1

1

See Wishlist: support for correlated union types #30581

const allConfigs = {
  "auth": auth,
  "config": config
}

function getConfig<
    CONFIG_NAME extends keyof typeof allConfigs,
    CONFIG_KEY extends keyof typeof allConfigs[CONFIG_NAME]
>(config: CONFIG_NAME, key: CONFIG_KEY): typeof allConfigs[CONFIG_NAME][CONFIG_KEY] {
    return allConfigs[config][key];
} 

Code in TS Playground

Sign up to request clarification or add additional context in comments.

4 Comments

Uh... why the switch/case statement? Does this version not work for some reason?
@jcalz Indeed - even in the unlikely case when someone passes unknown config name as any, TypeError "Cannot read properties of undefined" is thrown - no need to check it ourselves. I updated the answer.
... did you? I don't see it.
@jcalz Now I'm pretty sure the change is applied.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.