typescript - 如何在 TypeScript 接口(interface)对象中定义可选数据?

标签 typescript interface option-type

如何定义一个在对象内包含可选数据的 TypeScript 接口(interface)?
我的意思是:

export interface IMyInterface 
{
  name: string;
  data: 
  {
    size: number;
    color?: string;
    [any: string]?: any; // Error on this line!!!
  };
};

我知道您可以使用“?”定义可选数据像这样签名:

color?: string;

但是如何在对象内定义附加可选数据

let myObj: IMyInterface = 
{
   name: "theName",
   data:
   {
      size: 10,
      color: "red",
      moreOptionalData: { x: 'y' } // This line will throw an error (incampatable interface)
   }   
};

最佳答案

感谢 CRice 的评论和 OJ-Kwon 的洞察力,解决方案非常简单,我只需删除“?”标志。

export interface IMyInterface 
{
  name: string;
  data: 
  {
    size: number;
    color?: string;
    [any: string]: any; // optional additional data (no need for '?')
  };
};

let myObj: IMyInterface = 
{
   name: "theName",
   data:
   {
      size: 10,
      color: "red",
      moreOptionalData: { x: 'y' } // Now it's OK
   }   
};

关于typescript - 如何在 TypeScript 接口(interface)对象中定义可选数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48272172/

相关文章:

ios - Swift 主从模板应用之谜

java - 接口(interface)是否提供完整的抽象?如何?

swift - 将元组附加到元组数组

ios - Swift 可选值及其实例化

typescript - 如何在 VS 2017 中调试 typescript 代码?

haskell - 为什么 Haskell 没有在函数签名中推断数据类型的类型类?

web-services - Delphi Web 服务如何工作? (在运行时添加方法??)

typescript - 为什么通用类型 "T extends ' a' | 'b'“在检查参数是否等于联合类型值的情况下未正确解析?

javascript - 基于数组值切换 Angular 组件 CSS 类

static - typescript 类 : statics and inheritance