将 JSON 对象转换为 TypeScript 接口

本文将演示如何将一个 JSON 对象转换为 TypeScript 接口。

示例 JSON 对象:

{
  "three": "Hello %s",
  "num": {
    "zero": "not cats",
    "one": "only one cats",
    "other": "is %d cats"
  },
  "num1": {
    "zero": "not cats",
    "one": "only one cats",
    "other": "is %d cats"
  },
  "a": {
    "b": {
      "c": "s%2$s a %1$s"
    },
    "d": {
      "c": "s%2$s a %1$s"
    }
  }
}

对应的 TypeScript 接口:

interface TranslatedStrings {
  three: string;
  num: {
    zero: string;
    one: string;
    other: string;
  };
  num1: {
    zero: string;
    one: string;
    other: string;
  };
  a: {
    b: {
      c: string;
    };
    d: {
      c: string;
    };
  };
}

说明:

  • 接口中的属性名称与 JSON 对象中的键名保持一致。
  • 属性类型根据 JSON 对象中的值类型确定,例如字符串类型使用 string。
  • 接口可以嵌套,以反映 JSON 对象中的嵌套结构。

使用接口:

const translatedStrings: TranslatedStrings = {  
  three: 'Hello World',
  num: {
    zero: 'not cats',
    one: 'only one cats',
    other: 'is %d cats'
  },
  num1: {
    zero: 'not cats',
    one: 'only one cats',
    other: 'is %d cats'
  },
  a: {
    b: {
      c: 's%2$s a %1$s'
    },
    d: {
      c: 's%2$s a %1$s'
    }
  }
};

console.log(translatedStrings.three); // 输出: Hello World
console.log(translatedStrings.num.zero); // 输出: not cats
console.log(translatedStrings.a.b.c); // 输出: s%2$s a %1$s

总结:

将 JSON 对象转换为 TypeScript 接口可以方便地在代码中使用 JSON 数据,并提供类型检查和代码提示,提高代码可读性和可维护性。


原文地址: https://www.cveoy.top/t/topic/o4TJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录