I am having trouble specifying the type of TypeScript.You cannot compile with the following function toMap
:
const toMap=<Textends{}>(items:T[], key:keyofT)=>{
const map={};
items.forEach(item)=>{
map[item[key]]=item;// Error here
});
return map;
}
const data = [
{ id:'1', value: {foo:'bar'}},
{ id:'2', value: {hoge:'piyo'}},
];
toMap(data, 'id'); // = > {'1': {...}, '2': {...}}
<Textends{}>(items:T[], key:any):{[key:string]:T}
and I understand that we should compromise, but I would like to resolve this without using any
.
type StringPropertyNames<T>T>T>={[Kin keyof T]:T[K] extensions string?K:never of } in https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#example-2 with reference to
and FunctionPropertyNames>
Defining <Textends{}>(items:T[], key:StringPropertyNames<T>)
also failed.
I was able to write it in the form of a function that receives an array of types whose properties specified by key are string.
function to Map<Kextends string, Extends {[I in K]:string}>(items:T[], key:K){
const map: {[index:string]:T} = {};
items.forEach(item:E)=>{
constid=item[key];
map[id] = item;
});
return map;
}
© 2024 OneMinuteCode. All rights reserved.