【问题标题】:Is the Typescript interface correct for this object?该对象的 Typescript 接口是否正确?
【发布时间】:2020-08-24 18:26:58
【问题描述】:

我想为这些对象创建一个 Typescript 接口:

{
  "id": 34728,
  "url": "https://example.com/image.jpg",
  "commonNames": {
    "de": ["Apfel", "Kulturapfel"],
    "en": ["apple"],
    "th": ["แอปเปิล"]
  },
}

我的方法正确吗?我特别不确定 commonNames。

interface Food {
  id: number;
  url: string;
  commonNames: {
    [index: string]: string[];
  };
}

【问题讨论】:

  • 是否有预定义的 commonName 键列表('de'、'en'、'th'),或者它可以是任何字符串,直到运行时你才会知道哪些?如果它是任何字符串,那么你已经正确地完成了。
  • 是的,谢谢,它可以是任何字符串。如果我后来决定添加一个预定义的 CommonName 键列表会是什么样子?
  • 有几个选项,但我可能会用各种字符串定义一个联合类型,然后使用它。例如:type Language = 'de' | 'en' | 'th'commonNames: { [index in Language]: string[] }

标签: json typescript interface


【解决方案1】:

正如@Nicholas Tower's comment 中已经确认的那样,您的方法是正确的。

不过,我想提出一个小改进:您的类型定义中有三个strings。然而,这三个strings 实际上意味着完全不同的东西。所以,我要做的就是给他们一个type 别名:

type Uri      = string;
type Language = string;
type Name     = string;

interface Food {
  id: number;
  url: Uri;
  commonNames: {
    [index: Language]: Name[];
  };
}

这些只是别名,所以它们实际上并没有改变任何关于打字的东西。但是,它们使这些属性的含义更加清晰。

另外,type 别名为您提供了一个位置,您可以将 TSDoc 评论附加到:

/**
/ * A globally unique, monotonically increasing identifier for a dictionary entry
**/
type Id         = number;

/**
/ * A URI
**/
type Uri        = string;

/**
/ * A URI referencing a picture of the food
**/
type PictureUri = Uri;

/**
/ * An ISO 639-1:2002 Alpha-2 Language Code
**/
type Language   = string;

/**
/ * The name of the food
**/
type Name       = string;

interface Food {
  id: Id;
  url: PictureUri;
  commonNames: {
    [index: Language]: Name[];
  };
}

这当然是一个极端的例子,但它显示了type 文档别名的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2014-08-05
    • 2020-08-23
    • 2019-09-30
    • 2013-04-07
    • 2018-11-15
    • 1970-01-01
    相关资源
    最近更新 更多