Typescript: Cannot destructure a Readonly Tuple

Created on 2 Aug 2017  路  3Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.4.0

Code

// This is OK
type Tuple = [string, number]
const t : Tuple = ['string', 2]
const [s,n] = t

// This errors 
// [ts] Type 'Readonly<[string, number]>' is not an array type.
// const rs: string
type ReadonlyTuple = Readonly<[string, number]>
const rt : ReadonlyTuple = ['string', 2]
const [rs,rn] = rt

Expected behavior:
No errors

Actual behavior:
Error as above

Design Limitation

Most helpful comment

This is probably a limitation of the Readonly<> that causes it to lose the "array-ness" of the tuple type. You can work around it as follows:

type ReadonlyTuple = Readonly<[string, number]> & [string, number];
const rt: ReadonlyTuple = ['string', 2]
rt[0] = 'zero'; // error as expected, still read-only
const [rs,rn] = rt // no error, accepts as array type

All 3 comments

This is probably a limitation of the Readonly<> that causes it to lose the "array-ness" of the tuple type. You can work around it as follows:

type ReadonlyTuple = Readonly<[string, number]> & [string, number];
const rt: ReadonlyTuple = ['string', 2]
rt[0] = 'zero'; // error as expected, still read-only
const [rs,rn] = rt // no error, accepts as array type

ReadonlyTuple is mapped type, destructing requires array like type in your case

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nitzantomer picture nitzantomer  路  135Comments

tenry92 picture tenry92  路  146Comments

chanon picture chanon  路  138Comments

RyanCavanaugh picture RyanCavanaugh  路  205Comments

xealot picture xealot  路  150Comments