我正在嘗試輸入下面的實用程式函式,它接受一個陣列并回傳一個物件,如下所示
const convertListToMap = (list, key, secondKey) => {
const map = {};
for (const ele of list) {
map[ele[key]] = ele[secondKey]
}
return map;
}
console.log(convertListToMap([{name: 'isaac', age: 17}, {name: 'john', age: 20}], 'name', 'age'));
console.log(convertListToMap([{race: 'chinese', language: 'mandarin'}, {race: 'malay', language: 'melayu'}], 'race', 'language'));
正如你所知道的key,它secondKey是動態的,取決于引數list,所以我猜generics是要走的路。下面是我的嘗試
const convertListToMap = <
T extends object,
U extends keyof T,
V extends keyof T
>(
list: T[],
key: U,
secondKey: V
) => {
const map = {} as Record<U, V>;
for (const ele of list) {
map[ele[key]] = ele[secondKey];
}
return map;
};
但是,上面給了我錯誤Type 'T[U]' cannot be used to index type 'Record<U, V>',想知道我做錯了哪一部分?
更新
我的最新嘗試是更新的簽名map如下
const map = {} as Record<T[U], T[V]>;
for (const ele of list) {
map[ele[key]] = ele[secondKey];
}
return map;
通過最新的嘗試,map變數的值分配很好,但我在記錄宣告行出現錯誤并出現以下錯誤
Type 'T[U]' does not satisfy the constraint 'string | number | symbol'. Type 'T[keyof T]' is not assignable to type 'string | number | symbol'. Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'string | number | symbol'. Type 'T[string]' is not assignable to type 'string | number | symbol'. Type 'T[string]' is not assignable to type 'symbol'. Type 'T[keyof T]' is not assignable to type 'symbol'. Type 'T[U]' is not assignable to type 'symbol'. Type 'T[keyof T]' is not assignable to type 'symbol'. Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'symbol'. Type 'T[string]' is not assignable to type 'symbol'.ts(2344)
uj5u.com熱心網友回復:
最后一次嘗試的問題Record似乎只期望string | number | symbol,并且由于 TypeScript 不確定T[U]會是什么,因此它拋出了錯誤。我發現我們可以告訴 TS 多一點T,如下所示
const convertListToMap = <
T extends { [key: string|number]: string | number },
U extends keyof T,
V extends keyof T
>(
list: T[],
key: U,
secondKey: V
) => {
const map = {} as Record<T[U], T[V]>;
for (const ele of list) {
map[ele[key]] = ele[secondKey];
}
return map;
};
從上面的,我們告訴打字稿這T是要和物件key的string,其值是要去型別string | number,與,打字稿是快樂的定義Record<T[U], T[V]>
此解決方案效果很好,TS 可以正確推斷
const personObj = convertListToMap([{name: 'isaac', age: 17}, {name: 'john', age: 20}], 'name', 'age')
// const personObj: Record<string, number>
const languageObj = convertListToMap([{race: 'chinese', language: 'mandarin'}, {race: 'malay', language: 'melayu'}], 'race', 'language')
// const languageObj: Record<string,string>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311185.html
標籤:javascript typescript generics
