【问题标题】:How to: generic that accepts readonly types?如何:接受只读类型的泛型?
【发布时间】: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&lt;L extends readonly any[]&gt; = L
  • 谢谢@ford04 - 请问它如何接受只读和非只读类型作为参数?
  • 之前应该尝试过 - 效果很好 - 你能发布一个答案以便我验证它@ford04 吗?

标签: typescript typescript-typings typescript-generics


【解决方案1】:

是的,您可以在通用约束中使用 readonly 修饰符:

type DoSomethingWith<L extends readonly any[]> = L
//                             ^ add this

或者,在将keysas const 缩小后,您可以反过来删除readonly 标志:

type Mutable<T> = T extends object ? { -readonly [K in keyof T]: Mutable<T[K]> } : T

使用您的类型进行测试 (Playground):

type T1 = Mutable<Keys> // { a: ["a", "b", "c"]; d: ["d", "e", "f"]; }

type KeyKinds = {
    [K in keyof Keys]: DoSomethingWith<Mutable<Keys[K]>> // compiles now
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多