首页 > 解决方案 > TypeScript - 元素隐式具有“任何”类型 [...] 在类型上找不到具有“字符串”类型参数的索引签名

问题描述

我正在努力克服 TS 上的错误。

我根据我创建的 2 个接口(WalletInformationsEdit 和 UserInformationsEdit)定义值(在代码下方)

我遇到的问题是在 DB 查询之后的那一行,value[field]下划线表示:

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'.

我找到了 2 个解决方案来避免此错误消息,但我不好,因为它们使我的代码受到的保护较少:

1/ 在 TS 配置中,如果我取消 "strict": true 和 "noImplicitAny": true -> working

2/如果我用“任何”类型定义值,-> 工作

但我想两者都不值得。

你对处理这个案子有什么建议吗?

提前致谢,

保罗

    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 和 UserInformationsEdit 接口

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

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

标签: javascriptnode.jstypescript

解决方案


我终于找到了答案,在我的情况下声明索引签名,我不得不这样声明

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

} 

[key: string] -> 索引被读取为字符串

: 号码 | 字符串 | 布尔值 | undefined -> 构成我的接口的每种类型 + undefined 因为属性是可选的

感谢@DigitalDrifter 的链接:-)


推荐阅读