返回一个函数的结果,使其包含作为参数数组中元素的键。

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

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}

xy 在功能上等同于您提到的类型。

英文:

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.

playground

huangapple
  • 本文由 发表于 2023年3月7日 14:59:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658839.html
匿名

发表评论

匿名网友

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

确定