首页 > 解决方案 > 如何从键中派生 Typescript 类型的值

问题描述

我们如何根据对象的键值来定义对象的值的类型?

我尝试执行以下操作。但是,它似乎不是有效的语法:

type Config = {
    [Arg: string]: (arg: `Test-${Arg}`) => void
}

有没有办法做到这一点?

标签: typescripttypescript-typings

解决方案


没有使用类型变量是没有办法的。

type Config<A extends string> = {
  [K in A]: (arg: `Test-${K}`) => void
}

type X = 'Foo' | 'Bar'

const asConfig = <A extends string>(c: Config<A>): Config<A> => c

const config = asConfig({
  Foo: foo => {
    foo // 'Test-Foo'
  },
  Bar: bar => {
    bar // 'Test-Bar'
  }
})

操场

编辑:更新了 jcalz 的建议。


推荐阅读