假設我有這個:
export type ParamDecl = ["input" | "output", "float" | "int" | "bool", string][];
const params: ParamDecl = [["input", "float", "x"], ["output", "float", "a"], ["input", "int", "y"], ["output", "bool", "b"]];
我想把它變成這樣:
export type Converted = {
x: "float",
a: "float",
y: "int",
b: "bool"
};
通過使用泛型和映射型別(是的,我放棄了這"input" | "output"部分;我稍后會考慮)。我希望能夠做到這一點:
let dict: AsDictionary<typeof params>;
我嘗試使用以下映射型別:
export type AsDictionary<X extends ParamDecl> = { [K in keyof X as X[K][2]]: X[K][1] };
但我得到 2 個錯誤;我認為第二個是第一個的結果。

Type 'X[K][2]' is not assignable to type 'string | number | symbol'.
Type 'X[keyof X][2]' is not assignable to type 'string | number | symbol'.
Type 'X[string][2] | X[number][2] | X[symbol][2]' is not assignable to type 'string | number | symbol'.
Type 'X[string][2]' is not assignable to type 'string | number | symbol'.ts(2322)
Type '2' cannot be used to index type 'X[K]'.ts(2536)
我認為X[string][2]應該或多或少有效;如果有的話,唯一的問題是它應該是X[number][2]如果有的話,因為輸入型別它是一個陣列。
我究竟做錯了什么?
uj5u.com熱心網友回復:
這里的問題是您keyof X在映射型別中使用。X是一個具有許多其他屬性的陣列,例如pushorpop或length. 你不能索引它們,2因為它們不是元組/陣列。
您需要在 with 中映射元素的X聯合X[number]。
export type AsDictionary<X extends ParamDecl> = {
[K in X[number] as K[2]]: K[1]
};
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516367.html
標籤:打字稿仿制药
下一篇:如何使用打字稿泛型型別作為物件鍵
