Skip to content

Commit

Permalink
[solution]: en/easy-tuple-length.md (#339)
Browse files Browse the repository at this point in the history
update solution for tuple length to reject strings
  • Loading branch information
patxu authored Sep 25, 2023
1 parent 915e8fe commit da297ca
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions en/easy-tuple-length.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,16 @@ JavaScript. We can do the same in types as well:
type Length<T extends any> = T["length"];
```

But going that way we will get the compilation error Type 'length' cannot be
used to index type 'T'.”. So we need to give a hint to TypeScript and tell that
our input type parameter has this property:
But going that way we will get the compilation error `Type 'length' cannot be
used to index type 'T'.`. We could try to give a hint to TypeScript and tell that
our input type parameter has the `length` property:

```ts
type Length<T extends { length: number }> = T["length"];
```

An alternative solution:
However, in this case T encompasses both arrays and strings. Instead, check that T is an array
with:

```ts
type Length<T extends readonly any[]> = T["length"];
Expand Down

0 comments on commit da297ca

Please sign in to comment.