gpt4 book ai didi

typescript - 如何: generic that accepts readonly types?

转载 作者:行者123 更新时间:2023-12-04 14:16:16 25 4
gpt4 key购买 nike

给定一个列表上的 Action

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

或者在用 as const 缩小 keys 之后,你反过来删除 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
}

关于typescript - 如何: generic that accepts readonly types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60063641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com