Home > Net >  How to store object property values in an array, in typescript
How to store object property values in an array, in typescript

Time:04-26

I want to store the properties names of an object in an array, and store the corresponding value for each property in another array, the code succeeded in javascript but when I tried using it in typescript it throw an error: the code:

const newClinicalData = {
    id: '111',
    patient_id: '123',
    patient_national_id: '333',
    dm: 'yes',
    htn: 'no',
    hcv: 'yes',
    hbv: 'no',
    hiv: 'yes',
    hcv_vriology: 'no',
    hbv_virology: 'yes',
    hiv_virology: 'no',
    ckd: 'no',
    disability: 'no',
    cardiac: 'yes'
}

let newColumns = [];
let newEntries = [];
for (const column in newClinicalData) {
    newColumns.push(column);
    newEntries.push(newClinicalData[column]);
}

When I used the same code in typescript,I got the following error; when pushing data to newEnteries array: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Clinical_Data_Type'. No index signature with a parameter of type 'string' was found on type 'Clinical_Data_Type'."

CodePudding user response:

This is because column is only recognized as a string and not keyof typeof newClinicalData.

You'll need to tell Typescript that column is meant to be a key of your object by specifying

newEntries.push(newClinicalData[column as keyof typeof newClinicalData]);

Playground

  • Related