Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ Click the type names for complete docs.
- `HomomorphicOmit` - See [`Except`](source/except.d.ts)
- `IfAny`, `IfNever`, `If*` - See [`If`](source/if.d.ts)
- `MaybePromise` - See [`Promisable`](source/promisable.d.ts)
- `ReadonlyTuple` - See [`TupleOf`](source/tuple-of.d.ts)

## Tips

Expand Down
19 changes: 4 additions & 15 deletions source/readonly-tuple.d.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
/**
Creates a read-only tuple of type `Element` and with the length of `Length`.

@private
@see `ReadonlyTuple` which is safer because it tests if `Length` is a specific finite number.
*/
type BuildTupleHelper<Element, Length extends number, Rest extends Element[]> =
Rest['length'] extends Length ?
readonly [...Rest] : // Terminate with readonly array (aka tuple)
BuildTupleHelper<Element, Length, [Element, ...Rest]>;
import type {TupleOf} from './tuple-of.d.ts';

/**
Create a type that represents a read-only tuple of the given type and length.
Expand All @@ -32,12 +23,10 @@ guestFencingTeam.push('Sam');
//=> error TS2339: Property 'push' does not exist on type 'FencingTeam'
```

@deprecated This type will be removed in the next major version. Use the built-in `Readonly` type in combination with the {@link TupleOf} type instead, like `Readonly<TupleOf<Length, Element>>`.

@category Utilities
*/
export type ReadonlyTuple<Element, Length extends number> =
number extends Length
// Because `Length extends number` and `number extends Length`, then `Length` is not a specific finite number.
? readonly Element[] // It's not fixed length.
: BuildTupleHelper<Element, Length, []>; // Otherwise it is a fixed length tuple.
export type ReadonlyTuple<Element, Length extends number> = Readonly<TupleOf<Length, Element>>;

export {};
2 changes: 2 additions & 0 deletions source/tuple-of.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ type EmptyTuple = TupleOf<-3, string>;
//=> []
```

Note: If you need a readonly tuple, simply wrap this type with `Readonly`, for example, to create `readonly [number, number, number]` use `Readonly<TupleOf<3, number>>`.

@category Array
*/
export type TupleOf<Length extends number, Fill = unknown> = IfNotAnyOrNever<Length,
Expand Down