英文:
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>
}
英文:
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>
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论