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

getting type of dynamic key in typescript?

I have a object that looks roughly like this:

const colors = {
    gray: {
        50: "#f9fafb",
        100: "#f3f4f6",
    },
    red: {
        50: "#fef2f2",
        100: "#fee2e2",
        200: "#fecaca",
    }
}

I am creating a helper function that returns a color from the colors object:

interface GetColor {
    (selector: keyof typeof colors, tint: // ...?): // ...?
}

const getColor = (selector, tint) => {
        return colors[selector][tint];
}

how do I get correct typings for the parameters (infer tint based on selector value) and return value?

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 :

Here’s an inline example using generics. playground

const colors = {
    gray: {
        50: "#f9fafb",
        100: "#f3f4f6",
    },
    red: {
        50: "#fef2f2",
        100: "#fee2e2",
        200: "#fecaca",
    }
}

const getColor = <T extends keyof typeof colors, K extends keyof typeof colors[T]>(selector:T, tint:K): typeof colors[T][K] => {
        return colors[selector][tint];
}

const t1 = getColor('gray', 100)
const t2 = getColor('gray', 200) // Argument of type '200' is not assignable to parameter of type '100 | 50'

const t3 = getColor('red', 200)

const t4 = getColor('blue', 100) // Argument of type '"blue"' is not assignable to parameter of type '"gray" | "red"'
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