typescript / expert
Snippet
Readonly Tuple Slice Indexing for Buffer Segment Access
This snippet demonstrates zero-runtime-cost type manipulation via recursive tuple counters. By tracking array indices with accumulator tuple length parameters (`Index['length']`), TypeScript extracts sub-slices of fixed-size tuple types strictly during compilation, enabling precise binary header protocol validation.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type TupleSlice<T extends readonly unknown[],Start extends number,End extends number,Acc extends readonly unknown[] = [],Index extends readonly unknown[] = []> = Index["length"] extends End? Acc: Index["length"] extends Start? TupleSlice<T, Start, End, [...Acc, T[Index["length"]]], [...Index, unknown]>: Acc["length"] extends 0? TupleSlice<T, Start, End, Acc, [...Index, unknown]>: TupleSlice<T, Start, End, [...Acc, T[Index["length"]]], [...Index, unknown]>;type ByteHeader = readonly [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];type PNGMagicBytes = TupleSlice<ByteHeader, 0, 4>;
Breakdown
1
type TupleSlice<T extends readonly unknown[], Start extends number, End extends number...>
Defines a tail-recursive type utility that slice-extracts elements from tuple T between Start and End indices.
2
Index["length"] extends End ? Acc
Uses tuple length comparison as a type-level loop counter termination check.
3
type PNGMagicBytes = TupleSlice<ByteHeader, 0, 4>;
Slices the first 4 magic byte literal types from the ByteHeader tuple at compile time.