typescript / intermediate
Snippet
Immutable Array Pipeline Transformations using Readonly Types
Using readonly modifiers for array parameters prevents accidental mutation of input data during collection processing. Pipeline operations like filter and map produce new arrays, maintaining functional immutability and memory safety.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface Metric {readonly id: string;readonly value: number;}const rawDataset: readonly Metric[] = [{ id: "m1", value: 42 },{ id: "m2", value: -15 },{ id: "m3", value: 100 }];function processMetrics(data: readonly Metric[]): readonly number[] {return data.filter(metric => metric.value > 0).map(metric => metric.value * 2);}const processedData = processMetrics(rawDataset);
Breakdown
1
readonly id: string;
Ensures individual object properties cannot be modified after initialization.
2
const rawDataset: readonly Metric[] = [
Declares a read-only array that disallows array-mutating methods like push or pop.
3
function processMetrics(data: readonly Metric[]): readonly number[] {
Accepts a read-only dataset and promises to return a new read-only array of numbers.
4
.filter(metric => metric.value > 0).map(metric => metric.value * 2);
Chains non-mutating array methods to transform the data cleanly without modifying the source.