From 91a77de5b97b13f6c0b9748e2fbbbe274970df8c Mon Sep 17 00:00:00 2001 From: Jover Lee Date: Fri, 22 Nov 2024 13:17:55 -0800 Subject: [PATCH] Use more robust type narrowing for `Measurement` and `Collection` As suggested in review --- src/actions/measurements.ts | 19 +++++-------------- src/reducers/measurements/types.ts | 29 ++++++++++++++++++++++++----- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/src/actions/measurements.ts b/src/actions/measurements.ts index a996f84f6..6e4bc5a91 100644 --- a/src/actions/measurements.ts +++ b/src/actions/measurements.ts @@ -14,14 +14,14 @@ import { } from "./types"; import { Collection, - isCollection, - isMeasurement, + asCollection, + asMeasurement, isMeasurementsDisplay, measurementsDisplayValues, Measurement, MeasurementsDisplay, MeasurementsJson, - MeasurementsState + MeasurementsState, } from "../reducers/measurements/types"; /** @@ -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 @@ -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); diff --git a/src/reducers/measurements/types.ts b/src/reducers/measurements/types.ts index 2363ff202..05616a3a8 100644 --- a/src/reducers/measurements/types.ts +++ b/src/reducers/measurements/types.ts @@ -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 { + 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 { @@ -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 { + 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 {