【问题标题】:Nested TypeScript object with variable keys具有可变键的嵌套 TypeScript 对象
【发布时间】:2018-03-12 23:09:52
【问题描述】:

我有一个 JavaScript 方法,可以根据目录结构自动导入 JSON 模式。这意味着我有一个位于/path/to/my/file.json 的文件,然后将其加载到schemas.path.to.my.file

我使用以下 TypeScript 定义在 TypeScript 中使用我的代码,但无济于事。它不断给我关于no index signature 的错误,尽管似乎有一个。

import jsonschema = require("jsonschema");

interface NestedSchemas {
    [key: string]: NestedSchemas | jsonschema.Schema;
}

interface MySchemas {
    validator: jsonschema.Validator;
    initialized: boolean;
    walk: Promise<NestedSchemas>;
    schemas: NestedSchemas;
}

declare var _: MySchemas;
export = _;

当我尝试使用我的代码时,我看到我的 linter 弹出以下内容:

兴趣点是它首先显示Schema,然后是NestedSchemas(虽然在界面中以相反的方式定义),并且无论如何它都不会尝试解决它,因为它是一个字符串钥匙。

我在这里做错了什么?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    您可以像这样简化问题: 这给出了警告:

    interface NestedSchemas {
        [key: string]: NestedSchemas | string;
    }
    const themas: NestedSchemas = {};
    themas['0.1'].foo.bar.baz
    

    虽然不是这样:

    interface NestedSchemas {
        [key: string]: NestedSchemas;
    }
    const themas: NestedSchemas = {};
    themas['0.1'].foo.bar.baz
    

    这是因为 typescript 不知道 themas['0.1'] 的类型是 NestedSchemas 还是 string

    • 您可以通过强制转换来规避:

    (((themas['0.1'] as NestedSchemas).foo as NestedSchemas).bar as NestedSchemas).baz

    (我承认,不是很优雅)

    • 或者您可以使用用户定义的类型保护

    您应该阅读https://www.typescriptlang.org/docs/handbook/advanced-types.html 了解有关它的详细信息。

    【讨论】:

    • 但在这种情况下,我该如何定义树的“叶子”?
    • 不明白。你的意思是:((((themas['0.1'] as NestedSchemas).foo as NestedSchemas).bar as NestedSchemas).baz as string)
    猜你喜欢
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2022-11-30
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多