Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  81] [ 1]  / answers: 1 / hits: 7252  / 4 Years ago, wed, november 11, 2020, 12:00:00

I'm struggling to get over an error on TS.


I define value (below in the code) according 2 interfaces that I created (WalletInformationsEdit and UserInformationsEdit)


The problem that I encounter is at the line right after the DB query, value[field] is underlined saying :


Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'WalletInformationsEdit | UserInformationsEdit'.
No index signature with a parameter of type 'string' was found on type 'WalletInformationsEdit | UserInformationsEdit'.

I have find 2 solutions to avoid this error message, but I am not ok because they make my code less protected:


1/ In TS config, if I take off "strict": true and "noImplicitAny": true -> working


2/ if I define value with "any" type, -> working


But both are not worth it, I suppose.


Do you have any recommandation to handle this case ?


Thanks in advance,


Paul


    public async update(value: WalletInformationsEdit | UserInformationsEdit): Promise<any> {

try {

// saving id before elem treatment
const keepId = value.id
delete value.id

let filterFields = []
for (let elem of Object.keys(value)) {
filterFields.push(elem)
}

let i = 0;
let updateList = [];
for (const field of filterFields) {
updateList.push(`"${field}" = $${++i}`);
}

const preparedQuery = {
text: `UPDATE "${this.constructor.name.toLowerCase()}" SET
${updateList.join()}
WHERE id = $${++i}
RETURNING *
`,
values: [...filterFields.map((field) => value[field]), keepId],
};

const result = await db.query(preparedQuery);

return result.rows[0]

} catch (error) {
throw new Error(error.message)

}


}

WalletInformationsEdit and UserInformationsEdit interfaces


export interface UserInformationsEdit {
id?: number,
email?: string,
password?: string,
country?: string
}

export interface WalletInformationsEdit {
id?: number,
name?: string,
is_default?: boolean,
}

More From » node.js

 Answers
8

I finally find the answer, to declare the index signature in my case, i had to declare it this way


export interface WalletInformationsEdit {
[key: string]: number | string | boolean | undefined;
id?: number,
name?: string,
is_default?: boolean

}

[key: string] -> index is read as a string


: number | string | boolean | undefined -> each type that composed my interface + undefined because properties are optional


thanks @DigitalDrifter for the link :-)


[#2319] Saturday, November 7, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
shylaelisan questions
;