繁体   English   中英

Typescript:从 Object 键和数组字符串值生成类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM