【问题标题】:How to get object property values as type from a function argument如何从函数参数中获取对象属性值作为类型
【发布时间】:2021-07-24 20:50:02
【问题描述】:

这是我要实现的目标的简短示例

type Arg = {
  name: string
}

function fun(arg: Arg): // what do I return ? 
function fun (arg) {
  return {[arg.name]: true}
}

对此我有什么办法吗?

【问题讨论】:

  • 你想设置fun的输出吗?你能详细描述一下这个问题吗?
  • 你到底想要什么?
  • @MajidMohammadi 对不起,我认为这从代码示例中很明显。我想设置函数 fun 的返回类型。例如:fun({ name: 'John'}) 将返回 {John: true} 我不知道如何在 typescript 中描述这种输出
  • 我猜你想根据你的输入返回类型,this post 可以帮助你

标签: typescript


【解决方案1】:

我认为你正在寻找这样的东西:

type Arg<T extends string> = {
    name: T
}

function fun<Name extends string, T extends Arg<Name>>(arg: T): Record<T['name'], boolean>
function fun<Name extends string, T extends Arg<Name>>(arg: T) {
    return { [arg.name]: true }
}

const result = fun({ name: 'John' }) // Record<"John", boolean>

Playground

更多关于推断函数参数,你可以找到in my article

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多