如何在 TypeScript 接口中定义字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45780272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define an array of strings in TypeScript interface?
提问by AngeloC
I have an object like this:
我有一个这样的对象:
{
"address": ["line1", "line2", "line3"]
}
How to define address
in an interface? the number of elements in the array is not fixed.
如何address
在接口中定义?数组中的元素数量不固定。
回答by koe
interface Addressable {
address: string[];
}
回答by Mark Dolbyrev
It's simple as this:
这很简单:
address: string[]
回答by Daniel Khoroshko
Or:
或者:
{ address: Array<string> }
回答by Husniddin Qurbonboyev
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. There are two ways to declare an array:
TypeScript 支持数组,类似于 JavaScript。声明数组有两种方式:
- Using square brackets. This method is similar to how you would declare arrays in JavaScript.
- 使用方括号。此方法类似于您在 JavaScript 中声明数组的方式。
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
- 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];