简体   繁体   English

在 TypeScript 中更改导入的 JSON 的类型

[英]Change the type of an imported JSON in TypeScript

When importing a JSON file in a TypeScript project with the resolveJsonModule option enabled the TypeScript compiler is able to automatically infer the type of the imported JSON file. When importing a JSON file in a TypeScript project with the resolveJsonModule option enabled the TypeScript compiler is able to automatically infer the type of the imported JSON file. However, this type is too specific and I want to replace it with a more generic one.但是,这种类型太具体了,我想用更通用的替换它。 I tried to do this by writing a custom type definitions file:我试图通过编写自定义类型定义文件来做到这一点:

// file modules.d.ts

declare module "*.json" {
  const value: Record<string, string>;
  export default value;
}

but the TypeScript compiler ignores this definition.但 TypeScript 编译器会忽略此定义。

The only way that works for me is to use temporary variables, like this:对我有用的唯一方法是使用临时变量,如下所示:

import DATA_JSON from "./data.json";

const DATA  = DATA_JSON as Record<string, string>; // Use my own type instead of the inferred one.

export { DATA };

but this is boring.但这很无聊。 Is there any other way to give my own types to JSON files imported in TypeScript?有没有其他方法可以将我自己的类型赋予在 TypeScript 中导入的 JSON 文件?

you could try it with mapped types .您可以尝试使用映射类型 Not sure what structure/types you want to achieve but I believe it's the way to go.不确定您想要实现什么结构/类型,但我相信这是通往 go 的方式。

Having such requirement sounds like a good moment to start exploring advanced TS (I recommend Matt Pocock on yt)有这样的要求听起来像是开始探索高级 TS 的好时机(我推荐Matt Pocock on yt)

import DATA_JSON from './data.json';

const OWN_TYPED_DATA_JSON = DATA_JSON as unknown as {
   [key in keyof typeof DATA_JSON]: {
      [nestedKey in keyof typeof DATA_JSON[key]]: {
         [moreNestedKey in keyof typeof DATA_JSON[key][nestedKey]]: string
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM