Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.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 如何检查泛型对象上是否存在泛型属性<;T>;打字稿_Typescript_Typescript Generics - Fatal编程技术网

Typescript 如何检查泛型对象上是否存在泛型属性<;T>;打字稿

Typescript 如何检查泛型对象上是否存在泛型属性<;T>;打字稿,typescript,typescript-generics,Typescript,Typescript Generics,我正在将一个代码库从Javascript转换为Typescript,但这个函数有问题。我在第const valueAtKey=item[key]行收到一个typescript错误,说元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型“{}”。在类型{}上找不到具有“string”类型参数的索引签名。ts(7053) 我想我可以通过检查属性是否存在于T中来逃避错误,但即使在包装了if(输入项)之后,错误仍然不会消失 export const convertArrayTo

我正在将一个代码库从Javascript转换为Typescript,但这个函数有问题。我在第
const valueAtKey=item[key]
行收到一个typescript错误,说
元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型“{}”。在类型{}上找不到具有“string”类型参数的索引签名。ts(7053)

我想我可以通过检查属性是否存在于T中来逃避错误,但即使在包装了
if(输入项)
之后,错误仍然不会消失

export const convertArrayToDict = <T extends object>(arr: Array<T>, key: string): Record<string, T> => {
    const dict: Record<string, T> = {}
    // Iterate over each item, and add to new object using the value of the key as the new key
    for (const item of arr) {
        if (key in item) {
            const valueAtKey = item[key]
            if (valueAtKey && !dict[valueAtKey]) {
                dict[valueAtKey] = item
            }
        }
    }
    return dict
}
export const convertrarytodict=(arr:Array,key:string):Record=>{
常量dict:Record={}
//迭代每个项,并使用键的值作为新键添加到新对象
用于(arr的施工项目){
如果(输入项目){
const valueAtKey=项[键]
if(valueAtKey&!dict[valueAtKey]){
dict[valueAtKey]=项目
}
}
}
返回指令
}

似乎
arr
是一个键控对象数组,其中每个对象都有字符串键和字符串值。如果是这种情况,则只需更换:

<T extends object>

与:


或者,如果某些对象值可能未定义:

<T extends Record<string, string | undefined>

似乎
arr
是一个键控对象数组,其中每个对象都有字符串键和字符串值。如果是这种情况,则只需更换:

<T extends object>

与:


或者,如果某些对象值可能未定义:

<T extends Record<string, string | undefined>
记录实际上应该是记录记录实际上应该是记录