typescript - 如何从键中派生 Typescript 类型的值
问题描述
我们如何根据对象的键值来定义对象的值的类型?
我尝试执行以下操作。但是,它似乎不是有效的语法:
type Config = {
[Arg: string]: (arg: `Test-${Arg}`) => void
}
有没有办法做到这一点?
解决方案
没有使用类型变量是没有办法的。
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 的建议。
推荐阅读
- javascript - 我们如何将 Vue JS 与 ASP.NET MVC 和 nuget 包集成
- html - 在这段代码中,为什么两个段落都是蓝色的?
- android - React Native - 列表项之间的随机行
- laravel - Laravel 电子邮件验证模板位置
- java - com.mysql.cj.jdbc.exceptions.CommunicationsException:通信链路故障,由读取超时引起
- oauth - Google 登录按钮 - 什么可以防止某人欺骗另一个应用程序并窃取令牌?
- sql - 将表分离到不同的数据库是更安全还是更好
- php - PHP - 格式错误的 HTML 中的正则表达式
- javascript - Javascript - 防止意外的文本突出显示 onmousedown (firefox)
- object - E2E Protractor:页面对象映射找不到模块