【发布时间】:2023-03-16 20:34:02
【问题描述】:
为什么这不起作用?
class Demo<T, ArrayOfKeysOfT extends (keyof T)[]> {
constructor(args: {[index in keyof ArrayOfKeysOfT]: T[ArrayOfKeysOfT[index]]}) {
args;
}
}
我得到的错误说
类型
ArrayOfKeysOfT[index]不能用于索引类型T。
但是看起来这段代码应该没问题。我不确定这是设计使然还是 Typescript 中的错误。
更新
我意识到这里的问题是ArrayOfKeysOfT[index] 其中index 是keyof ArrayOfKeysOfT 类型不仅导致包含ArrayOfKeysOfT 的所有成员的类型,而且还包含数组的所有不同键一般(长度、推送、弹出等),这就是为什么它不能用于键入 T 类型。
我想要完成的是以下内容。
假设我定义了一些接口
interface Example {
one: string;
two: boolean;
}
那么这应该是允许的
new Demo<Example, ['one', 'two']>({
one: "some string",
two: false
});
这应该会导致编译器错误,因为 'two' 不在类型参数数组中
new Demo<Example, ['one']>({
one: "some string",
two: false
});
这应该会导致编译器错误,因为三不是第一个类型参数参数的键
new Demo<Example, ['one', 'two', 'three']>({
one: 'some string',
two: true,
three: 4
});
最后这应该不起作用,因为分配给 args 对象中成员“two”的值类型错误
new Demo<Example, ['one', 'two']>({
one: "some string",
two: "another string"
});
【问题讨论】:
-
如果我将它更改为
T[ArrayOfKeysOfT[number]],我只能编译它,但这不考虑index。那么,请问您到底想达到什么目的?在您看来,args应该是什么样子?index不应该是number类型,因为ArrayOfKeysOfT是Array?我不太明白keyof ArrayOfKeysOfT的用法,因为keyof any[]会返回number | "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | ... 13 more ... | "values"。 -
好点。更新以包含更多上下文。
标签: typescript