Skip to content

Commit

Permalink
Use more robust type narrowing for Measurement and Collection
Browse files Browse the repository at this point in the history
As suggested in review

<#1910 (comment)>
  • Loading branch information
joverlee521 committed Dec 7, 2024
1 parent 49ee53c commit 91a77de
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
19 changes: 5 additions & 14 deletions src/actions/measurements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ import {
} from "./types";
import {
Collection,
isCollection,
isMeasurement,
asCollection,
asMeasurement,
isMeasurementsDisplay,
measurementsDisplayValues,
Measurement,
MeasurementsDisplay,
MeasurementsJson,
MeasurementsState
MeasurementsState,
} from "../reducers/measurements/types";

/**
Expand Down Expand Up @@ -311,12 +311,7 @@ const parseMeasurementsJSON = (json: MeasurementsJson): MeasurementsState => {
}
});


if (isMeasurement(parsedMeasurement)) {
return parsedMeasurement;
} else {
throw new Error("Could not parse a valid measurement");
}
return asMeasurement(parsedMeasurement);
});

// Create groupings Map for easier access of sorted values and to keep groupings ordering
Expand All @@ -340,11 +335,7 @@ const parseMeasurementsJSON = (json: MeasurementsJson): MeasurementsState => {
})
);

if (isCollection(collection)) {
return collection;
} else {
throw new Error("Could not parse a valid collection");
}
return asCollection(collection);
});

const collectionKeys = collections.map((collection) => collection.key);
Expand Down
29 changes: 24 additions & 5 deletions src/reducers/measurements/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,16 @@ export interface Measurement {
[key: string]: string | number
}

export function isMeasurement(x: any): x is Measurement {
return Boolean(x[measurementIdSymbol] !== undefined && x.strain && x.value !== undefined)
export function asMeasurement(x: Partial<Measurement>): Measurement {
if (x[measurementIdSymbol] !== undefined && x.strain && x.value !== undefined) {
return {
...x,
[measurementIdSymbol]: x[measurementIdSymbol],
strain: x.strain,
value: x.value,
}
}
throw new Error("Measurement is partial.");
}

export interface Collection {
Expand All @@ -80,15 +88,26 @@ export interface Collection {
x_axis_label: string
}

export function isCollection(x: any): x is Collection {
return Boolean(
export function asCollection(x: Partial<Collection>): Collection {
if (
x.fields &&
x.filters &&
x.groupings &&
x.key &&
x.measurements &&
x.x_axis_label
);
){
return {
...x,
fields: x.fields,
filters: x.filters,
groupings: x.groupings,
key: x.key,
measurements: x.measurements,
x_axis_label: x.x_axis_label,
}
}
throw new Error("Collection is partial.");
}

export interface MeasurementsState {
Expand Down

0 comments on commit 91a77de

Please sign in to comment.