简体   繁体   English

接口数组中的打字稿命名定义

[英]Typescript named definition in interface Array

Let's say for example I have an interface which defines a boolean value and optional string: 例如,假设我有一个定义布尔值和可选字符串的接口:

Example

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

Now later in the code I want to use it: 现在在代码后面,我想使用它:

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

I got this working. 我工作了。 However, I would like to add more context to the Interface. 但是,我想为接口添加更多上下文。 The boolean should be named errorOccured and the string should be named message . 布尔值应命名为errorOccured ,字符串应命名为message

Tried 试着

I was thinking about the following: 我在考虑以下问题:

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

Might be something obvious that I'm missing, but I just don't get it. 可能是我想念的明显东西,但是我不明白。

There is an existing feature request for named tuples in TypeScript, but they are not currently supported. TypeScript中已存在对命名元组的功能请求 ,但当前不支持它们。

In the mean time, you can either use the unnamed tuple like you have, or use an object: 同时,您既可以使用未命名的元组,也可以使用对象:

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

Another option depending on your use case may be for errorOccurred to be implicit based on whether there is an error object at all or whether it has a message . 取决于您的用例的另一个选项可能是根据是否有错误对象或是否有message来将errorOccurred隐含。

With the name of your interface, I would have directly put the properties into it : 使用您的接口名称,我将直接将属性放入其中:

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

and your object error should be of type IError . 并且您的对象error应为IError类型。

And for the implementation of this interface, you can set independantly both parameters... 为了实现此接口,您可以分别设置两个参数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM