![](/img/trans.png)
[英]How to define array typescript interface with optional unique strings?
[英]How to define an array of strings in TypeScript interface?
我有一個這樣的對象:
{
"address": ["line1", "line2", "line3"]
}
如何在接口中定義address
? 數組中的元素數量不固定。
interface Addressable {
address: string[];
}
數組是一種特殊的數據類型,它可以使用特殊的語法順序存儲不同數據類型的多個值。
TypeScript 支持數組,類似於 JavaScript。 聲明數組有兩種方式:
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
兩種方法產生相同的輸出。
當然,你總是可以像下面這樣初始化一個數組,但是你不會得到 TypeScript 類型系統的優勢。
let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];
這很簡單:
address: string[]
或者:
{ address: Array<string> }
我認為最好的方法是: type yourtype = { [key: string]: string[] }
這是我來這里的答案:
enum Lines {
"line1",
"line2",
"line3",
}
interface Addressable {
address: keyof typeof Lines;
}
非常簡單的方法:
interface IQuestion {
question: string[];
testCase: number[];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.