我可以为以编程方式生成的 TypeScript interface/type 的键添加前缀或后缀吗?
Can I add a prefix or suffix to the keys of a TypeScript interface/type which is programmatically generated?
我想知道,是否可以为使用字符串数组作为键的 TypeScript 类型添加前缀或后缀。
type First = {
one: string
two: string
}
type Second = keyof First
type Third = {
[S in Second]: any
}
通过这种方法,Third 接受任何类型的属性 one
& two
。这太棒了,因为我只需要更改第一种类型就可以更新其他类型。
现在我想要第四种类型,它与 Third
完全相同,但我想为键添加前缀。比如美元符号什么的。
想要的结果:
type Fourth = {
$one: any
$two: any
}
我可以硬编码,但如果第一种类型已更改,我将不得不调整第四种类型。
谢谢。
TS 4.1 has support for easy key remapping 使用模板文字类型:
type First = {
one: string
two: string
}
type Fourth = {
[K in keyof First as `$${K}`]: any
}
如果您想使用与每个键关联的原始类型而不是 any
(如果您使用的是 TS,您应该尽可能避免使用 any
,毕竟!),替换
: any
和
: First[K]
我想知道,是否可以为使用字符串数组作为键的 TypeScript 类型添加前缀或后缀。
type First = {
one: string
two: string
}
type Second = keyof First
type Third = {
[S in Second]: any
}
通过这种方法,Third 接受任何类型的属性 one
& two
。这太棒了,因为我只需要更改第一种类型就可以更新其他类型。
现在我想要第四种类型,它与 Third
完全相同,但我想为键添加前缀。比如美元符号什么的。
想要的结果:
type Fourth = {
$one: any
$two: any
}
我可以硬编码,但如果第一种类型已更改,我将不得不调整第四种类型。
谢谢。
TS 4.1 has support for easy key remapping 使用模板文字类型:
type First = {
one: string
two: string
}
type Fourth = {
[K in keyof First as `$${K}`]: any
}
如果您想使用与每个键关联的原始类型而不是 any
(如果您使用的是 TS,您应该尽可能避免使用 any
,毕竟!),替换
: any
和
: First[K]