我正在尝试修复这些错误,但不知道该怎么做。如果您是 TS 方面的专家,请帮助我。 Algowiki
const a = {
a: 'value 1',
b: 'value 2',
c: {
k: 'value 3'
}
};
type ObjType = typeof a;
function funArray<
K extends keyof ObjType = keyof ObjType,
D extends ObjType[K] = ObjType[K]
>(arg: [K, keyof D]) {
const oneLvl = a[arg[0]];
// Issue # 1
// Type 'keyof D' cannot be used to index type '{ a: string; b: string; c: { k: string; }; }[K]'.
const secondLvl = oneLvl[arg[1]];
console.log(secondLvl);
}
funArray(['c', 'k']);
// Works as expected
funArray(['c', 'k']);
// Issue # 2
// Type '"k"' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 27 more ... | "padEnd"'.
funArray(['a', 'k']);
答案 0 :(得分:0)
去掉第二个泛型:
const a = {
a: 'value 1',
b: 'value 2',
c: {
k: 'value 3'
}
};
type ObjType = typeof a;
function funArray<
K extends keyof ObjType,
>(arg: [K, keyof ObjType[K]]) {
const fst = arg[0];
const scd = arg[1]
const oneLvl = a[fst];
const secondLvl = oneLvl[scd];
console.log(secondLvl);
}
funArray(['c', 'k']);
// Works as expected
funArray(['c', 'k']);
// This error is expected, because `k` can be used as a key to a['a']
funArray(['a', 'k']);
第三个例子没有问题。预计会出现此错误