Understanding How to Write an Object, Type-Limited Key Name

Asked 2 months ago, Updated 2 months ago, 4 views

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 FunctionPropertyNames>Defining and <Textends{}>(items:T[], key:StringPropertyNames<T>) also failed.

typescript

2022-09-30 14:23

1 Answers

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;
}


2022-09-30 14:23

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.