【问题标题】:Dynamically generated keys with Typescript and JSON使用 Typescript 和 JSON 动态生成的密钥
【发布时间】:2021-06-18 04:53:13
【问题描述】:

所以我正在使用 Typescript 和 React native 开发应用程序。我有 json 文件,其中包含一些我需要从我的应用程序访问的扑克手信息。

JSON 看起来像这样:

{
  "22": [
    [
      0,
      20
    ]
  ],
  "32o": [
    [
      0,
      20
    ]
  ],
  "32s": [
    [
      0,
      20
    ]
  ],
  "33": [
    [
      0,
      20
    ]
  ],

我正在导入 json 数据

import * as pdata from './push.json';

数据可以这样访问:

pdata['AA'][0][1]

但是,如果我尝试使用像这样动态创建的键来访问 json

currentHand = '32o';
console.log(pdata[currentHand][0][1]);

我收到错误消息“元素隐式具有 'any' 类型,因为 'string' 类型的表达式不能用于索引类型 '...' 没有找到带有 'string' 类型参数的索引签名输入 '{ "22": number[][];...'.

由于大量的密钥,硬编码所有不同的可能性是不可行的。 我一直在寻找答案,但没有找到任何有效的方法。

【问题讨论】:

    标签: json typescript


    【解决方案1】:

    由于您声明 currentHand 没有 const,Typescript 期望 currentHand 变量值可以/将被更改,并且它假定 currentHand 类型为 string

    现在如果你用const声明它:

    import data from "./push.json";
    
    const currentHand = "22";
    console.log(data[currentHand][0][1]);
    

    currentHand的类型将是"22"而不是string,并且不再出现错误

    由于大量的密钥,硬编码所有不同的可能性是不可行的。我一直在寻找答案,但没有找到任何有效的方法。

    试试这个

    type DataKey = keyof typeof data; // DataKey type is "22" | 32o" | "32s" | ...
    
    const currentHand: DataKey = "22";
    // or
    const currentHand = "22" as DataKey;
    
    console.log(data[currentHand][0][1]);
    

    另一种方式:

    import data from "./push.json";
    
    const dynamicData = <Data>(<any>data);
    
    type Data = {
      [key: string]: [number[]];
      // or if value structure is always the same
      [key: string]: [[number, number]];
    };
    
    
    let currentHand = "22";
    console.log(dynamicData[currentHand][0][1]); 
    

    【讨论】:

    • 我也没有让它工作,但还是谢谢。我找到了使用quicktype.io转换器的解决方案。
    【解决方案2】:

    我使用https://quicktype.io/ 找到了解决方案。 将生成的转换器保存在 Convert.ts 中,可以像这样访问 JSON 数据:

    import * as pdata from './push.json';
    import { Convert } from './Convert'
        
    const pushHands = Convert.toHands(JSON.stringify(pdata));
    var ch = '42o';
    console.log(pushHands['default'][ch][0][1]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2020-12-12
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多