在清单上采取行动
type DoSomethingWith<L extends any[]> = L
我想要做的就是这样
const keys = {
a: ['a', 'b', 'c'] as ['a', 'b', 'c'],
d: ['d', 'e', 'f'] as ['d', 'e', 'f'],
}
type Keys = typeof keys
type KeysWithSomething = {
[K in keyof Keys]: DoSomethingWith<Keys[K]>
}
但是为了避免冗余(在可能更长的列表上),我希望能够这样写:
const keys = {
a: ['a', 'b', 'c'] as const,
d: ['d', 'e', 'f'] as const,
}
type Keys = typeof keys
type DoSomethingWith<L extends any[]> = L
type KeyKinds = {
[K in keyof Keys]: DoSomethingWith<Keys[K]>
// ^^^^^^^: Type '{ a: readonly ["a", "b", "c"]; d: readonly ["d", "e", "f"]; }[K]' does not satisfy the constraint 'any[]'.
}
错误是我尝试传递一个只读类型DoSomething
,期望该类型具有通用列表类型(any[]
),这是一种指定DoSomething
它也应接受只读元素的方式吗?
是的,您可以readonly
在通用约束中使用修饰符:
type DoSomethingWith<L extends readonly any[]> = L
// ^ add this
或者你去倒过来,取下readonly
标志,已经缩小后keys
用as const
:
type Mutable<T> = T extends object ? { -readonly [K in keyof T]: Mutable<T[K]> } : T
用您的类型进行测试(游乐场):
type T1 = Mutable<Keys> // { a: ["a", "b", "c"]; d: ["d", "e", "f"]; }
type KeyKinds = {
[K in keyof Keys]: DoSomethingWith<Mutable<Keys[K]>> // compiles now
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句