简体   繁体   English

如何在 TypeScript 接口中定义字符串数组?

[英]How to define an array of strings in TypeScript interface?

I have an object like this:我有一个这样的对象:

{
  "address": ["line1", "line2", "line3"]
}

How to define address in an interface?如何在接口中定义address the number of elements in the array is not fixed.数组中的元素数量不固定。

interface Addressable {
  address: string[];
}

An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax.数组是一种特殊的数据类型,它可以使用特殊的语法顺序存储不同数据类型的多个值。

TypeScript supports arrays, similar to JavaScript. TypeScript 支持数组,类似于 JavaScript。 There are two ways to declare an array:声明数组有两种方式:

  1. Using square brackets.使用方括号。 This method is similar to how you would declare arrays in JavaScript.此方法类似于在 JavaScript 中声明数组的方式。
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
  1. Using a generic array type, Array.使用通用数组类型 Array。
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];

Both methods produce the same output.两种方法产生相同的输出。

Of course, you can always initialize an array like shown below, but you will not get the advantage of TypeScript's type system.当然,你总是可以像下面这样初始化一个数组,但是你不会得到 TypeScript 类型系统的优势。

let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];

Source资源

这很简单:

address: string[]

或者:

{ address: Array<string> }

我认为最好的方法是: type yourtype = { [key: string]: string[] }

This is the answer I came here for:这是我来这里的答案:

enum Lines {
  "line1",
  "line2",
  "line3",
}

interface Addressable {
   address: keyof typeof Lines;
}

Here is how the cool kids do it nowadays.以下是当今酷孩子们的做法。

export type stringArray = [string][number][];

Explanation:解释:

[string] creates a tuple of string [string]创建一个字符串元组

[number] cast the tuple into a string [number]将元组转换为字符串

[] declares it as an array []将其声明为数组

For non believers, here is the proof:对于非信徒,以下是证据:

在此处输入图像描述

Very simple method:非常简单的方法:

interface IQuestion {
 question: string[];
 testCase: number[];
}

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

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