【发布时间】:2020-05-20 15:36:17
【问题描述】:
给定一个列表上的动作
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 指定它也应该接受只读元素的方法吗?
【问题讨论】:
-
type DoSomethingWith<L extends readonly any[]> = L -
谢谢@ford04 - 请问它如何接受只读和非只读类型作为参数?
-
之前应该尝试过 - 效果很好 - 你能发布一个答案以便我验证它@ford04 吗?
标签: typescript typescript-typings typescript-generics