Home > Enterprise >  Modify typescript type of list to create a key value type
Modify typescript type of list to create a key value type

Time:01-09

While recently playing around with typescript type manipulation I tried to modify the type below

type setOfFunctions = [{
    name: 'hi',
    fun: () => number
}, {
    name: 'world',
    fun: () => string
}]

to archive the following type

type MyFunctions = {
    hi: () => number,
    world: () => string
}

I tried with the following type

type MyFunctions = {
    [key in setOfFunctions[number]["name"]] : setOfFunctions[number]["fun"]
}

But that ends up with

type MyFunctions = {
    hi: (() => number) | (() => string);
    world: (() => number) | (() => string);
}

CodePudding user response:

With the current implementation setOfFunctions[number]["fun"] will get both of the types in one, need to filter it somehow.

I have this.

Using a "filter" with a generic and an extends operation, if there is a match with the current key, infer the type of the function and use it as the value.

If theres no match just discard the function type with never

type setOfFunctions = [{
    name: 'hi',
    fun: () => number
}, {
    name: 'world',
    fun: () => string
}]

type getPropertieFnType<T extends setOfFunctions[number], key extends string> = T extends { name: key, fun: infer K } ? K : never

type MyFunctions  = {
    [key in setOfFunctions[number]["name"]]: getPropertieFnType<setOfFunctions[number], key>
}

Playground

  • Related