可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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