【问题标题】:How do I access the properties of a generic object by index in TypeScript?如何在 TypeScript 中通过索引访问通用对象的属性?
【发布时间】:2019-02-13 16:39:34
【问题描述】:

我有以下函数,它遍历对象的所有属性并将它们从 ISO 字符串转换为日期:

function findAndConvertDates<T>(objectWithStringDates: T): T {

    for (let key in Object.keys(objectWithStringDates)) {

        if (ISO_REGEX.test(objectWithStringDates[key])) {
            objectWithStringDates[key] = new Date(objectWithStringDates[key]);

        } else if (typeof objectWithStringDates[key] === 'object') {
            objectWithStringDates[key] = findAndConvertDates(
                objectWithStringDates[key]
            );
        }
    }
    return objectWithStringDates;
}

TypeScript 一直告诉我Element implicitly has an 'any' type because type '{}' has no index signature - 指的是objectWithStringDates[key] 的众多实例。

考虑到对象是作为通用对象传入的,如果没有明确的索引签名,我将如何设置访问这些属性?

(否则如何提供索引签名或抑制此错误?)

谢谢!

【问题讨论】:

    标签: node.js typescript generics typescript-generics index-signature


    【解决方案1】:

    你可以像这样制作一个可索引的签名:

    function findAndConvertDates&lt;T extends { [key: string]: any }&gt;(objectWithStringDates: T): T {

    【讨论】:

    • 我试过这个export interface IGApiResponse&lt;T extends {[key:string] : any}&gt; extends GaxiosResponse&lt;T&gt; {}; let tmpData: IGApiResponse&lt;GoogleApiSchema&gt;; 但是当试图获取 tmp 数据的属性之一时,我得到了脚本类型的错误:` const test = tmpData.data["test"]` 错误:@ 987654323@。如果我添加any,没有错误,但类型不安全...` const test =( tmpData.data as any)["test"]`
    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 2016-05-09
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2017-11-17
    相关资源
    最近更新 更多