How do I declare a read-only array tuple in TypeScript?

匿名 (未验证) 提交于 2019-12-03 08:50:26

问题:

We can declare a typed tuple in TypeScript, for example, with the type annotation [string, number]. This means an array of 2 elements where the first element needs to be a string and the second a number.

We can also declare read-only arrays with ReadonlyArray<string> which means a read-only array of strings.

Now I want to have a read-only tuple like in the first example, but I want it to be read-only like in the second example. How would I declare that?

回答1:

Since the type [string, number] already is an Array, you can simply use:

Readonly<[string, number]>

Example:

let tuple: Readonly<[string, number]> = ['text', 3, 4, 'another text'];  tuple[0] = 'new text'; //Error (Readonly)  let string1: string = tuple[0]; //OK! let string2: string = tuple[1]; //Error (Type number) let number1: number = tuple[0]; //Error (Type string) let number2: number = tuple[1]; //OK! let number3: number = tuple[2]; //Error (Type any) 


回答2:

Readonly<[string, T]> doesn't allow destruction. For example

const tuple: Readonly<[string, number]> = ["text", 4]  const [n, v] = tuple // error TS2488: Type 'Readonly<[string, number]>' must have a '[Symbol.iterator]()' method that returns an iterator. 

So, it's better to use a custom interface

export interface Entry<T> {     readonly [0]: string     readonly [1]: T     readonly [Symbol.iterator]: () => IterableIterator<string|T> } 

For example

const tuple: Entry<number> = ["text", 4]  const [name, value] = tuple // ok const nameCheck: string = name const valueCheck: number = value 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!