英文:
Type the return of a function such that it contains keys that are elements in an argument array
问题
我有一个函数:
type Action = 'doX' | 'doY'
function canIPerform(actions: Action[]) : {[action: string]: boolean} {
// 一些业务逻辑
return {'doX': true}
}
我想要的是使返回的映射只包含作为参数传递的键:
let x = canIPerform(['doX'])
// x 应该被类型化为 {[k in 'doX']: boolean}
let x = canIPerform(['doY', 'doX'])
// x 应该被类型化为 {[k in 'doX' | 'doY']: boolean}
第一个问题很简单,数组是运行时的,但我可以通过要求使用 const
来绕过它:
let x = canIPerform(['doX', 'doY'] as const)
尽管我尝试了很多方法,但我似乎找不到一种类似于 keyof
的方法,可以用于元组。
英文:
So I have a function:
type Action = 'doX' | 'doY'
function canIPerform(actions: Action[]) : {[action: string]: Boolean} {
// Some business logic
return {'doX': true}
}
What I want is to type it such that the returned map only contains keys that were passed in the argument:
let x = canIPerform(['doX'])
// x should be typed as {[k in 'doX']: boolean}
let x = canIPerform(['doY', 'doX'])
// x should be typed as {[k in 'doX' | 'doY']: boolean}
The first problem is simply the fact that arrays are runtime, but I can kind of circumvent it by requiring that they be called using const
:
let x = canIPerform(['doX', 'doY'] as const)
although I have found no way of "forcing" this. I tried a bunch of things, but I can't seem to find some equivalent of keyof
that kind of works for tuples.
答案1
得分: 1
这个问题是否已解决:
type Action = 'doX' | 'doY'
function canIPerform<T extends Action[]>(actions: T) : Record<T[number], boolean> {
// 一些业务逻辑
return { [actions[0]]: true }
}
let x = canIPerform(['doX'])
// ^?
// x 应该被定义为 {[k in 'doX']: boolean}
let y = canIPerform(['doY', 'doX'])
// ^?
// x 应该被定义为 {[k in 'doX' | 'doY']: boolean}
x
和 y
在功能上等同于您提到的类型。
英文:
Does this solve your issue:
type Action = 'doX' | 'doY'
function canIPerform<T extends Action[]>(actions: T) : Record<T[number], boolean> {
// Some business logic
return { [actions[0]]: true }
}
let x = canIPerform(['doX'])
// ^?
// x should be typed as {[k in 'doX']: boolean}
let y = canIPerform(['doY', 'doX'])
// ^?
// x should be typed as {[k in 'doX' | 'doY']: boolean}
x
and y
will functionally be equivalent to the types you have mentioned.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论