Home > Mobile >  getting type of dynamic key in typescript?
getting type of dynamic key in typescript?

Time:12-26

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?

CodePudding user response:

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"'
  • Related