[英]How to generate an object from an array where the keys are the words and the values are the string lenths?
[英]Typescript: Generate Type from Object keys and Array string values
我正在寻找从对象的键和 arrays 的字符串值生成类型。 该类型需要代表所有可能的字符串,即
const Actions = {
foo: ['bar', 'baz'],
}
# type generated from Actions to equal:
type ActionsType = 'foo' | 'bar' | 'baz'
我需要保留Actions
因为它要传递给一个方法,因此:
const Actions = {
foo: ['bar', 'baz'],
} as const
type ActionsType = keyof typeof Actions | typeof Actions[keyof typeof Actions][number]
虽然正确生成类型不允许我将Actions
传递给期望Record<string, string[]>
的方法,因为键和值变为只读。
如何生成所需的类型,同时仍然能够将Actions
用作非只读 Object?
这是一个简单的解决方案,可以将const 断言/ 的readonly
性恢复as const
:
type Mutable<T> = {-readonly [K in keyof T]: Mutable<T[K]>}
以下将使用类型断言和足够的类型安全进行编译:
type T1 = Mutable<typeof Actions> // { foo: ["bar", "baz"]; } function foo(a: Record<string, string[]>) {} foo(Actions as Mutable<typeof Actions>) // works
请注意, Actions
object 可能会在foo
内部发生变异,因此您最好也将其在包含模块中视为可变的。 更简洁的替代方法是更改foo
签名以接收readonly
arrays:
function foo2(a: Record<string, readonly string[]>) {} foo2(Actions) // works without type assertion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.