Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何:接受只读类型的泛型?_Typescript_Typescript Typings_Typescript Generics - Fatal编程技术网

Typescript 如何:接受只读类型的泛型?

Typescript 如何:接受只读类型的泛型?,typescript,typescript-typings,typescript-generics,Typescript,Typescript Typings,Typescript Generics,在列表上给定一个操作 type DoSomethingWith<L extends any[]> = L 类型DoSomethingWith=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

在列表上给定一个操作

type DoSomethingWith<L extends any[]> = L
类型DoSomethingWith=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 key={
a:['a','b','c']作为['a','b','c'],
d:['d','e','f']作为['d','e','f'],
}
类型键=类型键
类型keys with something={
[K in keyof Keys]:DoSomethingWith
}
但为了避免重复(在可能更长的列表上),我希望能够这样写:

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[]'.
}
const key={
a:[a',b',c']作为常量,
d:[d',e',f']作为常量,
}
类型键=类型键
类型DoSomethingWith=L
类型键种类={
[K in keyof Keys]:DoSomethingWith
//类型“{a:readonly[“a”、“b”、“c”];d:readonly[“d”、“e”、“f”];}[K]”不满足约束“any[]”。
}
错误是我试图在
DoSomething
上传递一个只读类型,该类型预期为泛型列表类型(
any[]

它们是一种指定DoSomething也应接受只读元素的方法吗?

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

type DoSomethingWith<L extends readonly any[]> = L
//                             ^ add this
使用您的类型()进行测试:

type T1=Mutable/{a:[“a”、“b”、“c”];d:[“d”、“e”、“f”];}
类型键种类={
[K in keyof Keys]:DoSomethingWith//现在编译
}

键入DoSomethingWith=L
谢谢@ford04-我可以问一下它如何接受只读类型和非只读类型作为参数吗?应该在之前尝试过-效果很好-你能发布一个答案以便我在@ford04验证它吗?
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
}