修改 TypeScript 中的列表类型以创建一个键值类型。

huangapple go评论78阅读模式
英文:

Modify typescript type of list to create a key value type

问题

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

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

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);
}

答案1

得分: 1

使用当前的实现,setOfFunctions[number]["fun"] 将同时获取两种类型,需要以某种方式进行筛选。

我有以下内容。

使用一个带有泛型和 extends 操作的“filter”,如果当前键有匹配项,则推断函数的类型并将其用作值。

如果没有匹配项,就将函数类型丢弃为 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

英文:

With the current implementation setOfFunctions[number][&quot;fun&quot;] 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: &#39;hi&#39;,
    fun: () =&gt; number
}, {
    name: &#39;world&#39;,
    fun: () =&gt; string
}]

type getPropertieFnType&lt;T extends setOfFunctions[number], key extends string&gt; = T extends { name: key, fun: infer K } ? K : never

type MyFunctions  = {
    [key in setOfFunctions[number][&quot;name&quot;]]: getPropertieFnType&lt;setOfFunctions[number], key&gt;
}

Playground

huangapple
  • 本文由 发表于 2023年1月9日 00:22:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定