【发布时间】:2020-10-12 20:23:22
【问题描述】:
是否可以为键值是文字键名本身的对象定义 TypeScript 类型?例如:
declare const $: SpecialGenericType
$.prop // typed as the literal value "prop"
const values = [
$.a,
$.b,
$.c
] as const
// values has the type (and value) ["a", "b", "c"]
$ 对象可以使用代理来实现,但我不确定如何实现SpecialGenericType。该类型需要允许任何字符串作为键,但需要将值键入为其键名的字符串文字(因此Record<string, string> 在这种情况下不起作用)。例如,上面的values 将具有元组类型["a", "b", "c"]。
【问题讨论】:
标签: typescript typescript-generics conditional-types mapped-types