【问题标题】:Typescript named definition in interface Array接口数组中的打字稿命名定义
【发布时间】:2019-05-29 14:02:39
【问题描述】:

假设我有一个定义布尔值和可选字符串的接口:

示例

interface IError {
  error: [boolean, string?];
}

现在我想在后面的代码中使用它:

if (somethingTrue) {
  error: [false]
} else {
  error: [true, "Error occurred because of foo"]
}

我得到了这个工作。但是,我想为界面添加更多上下文。布尔值应命名为errorOccured,字符串应命名为message

试过

我正在考虑以下问题:

interface IError {
  error: [errorOccured: boolean, message: string?];
}

我可能缺少一些明显的东西,但我就是不明白。

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    TypeScript 中的命名元组有 an existing feature request,但目前不支持。

    同时,你可以像你一样使用未命名的元组,或者使用一个对象:

    interface IError {
      errorOccurred: boolean;
      message?: string;
    }
    

    根据您的用例,另一个选项可能是 errorOccurred 根据是否存在错误对象或是否有 message 是隐式的。

    【讨论】:

      【解决方案2】:

      用你的接口名称,我会直接把属性放进去:

      interface IError {
        errorOccurred: boolean;
        message?: string;
      }
      

      你的对象error应该是IError类型。

      对于这个接口的实现,你可以独立设置两个参数...

      【讨论】:

        猜你喜欢
        • 2020-12-22
        • 2022-09-27
        • 2023-01-05
        • 1970-01-01
        • 2018-08-24
        • 1970-01-01
        • 2015-08-12
        • 2021-02-01
        • 2016-03-08
        相关资源
        最近更新 更多