Skip to content

Commit

Permalink
front: replace casts with assertions
Browse files Browse the repository at this point in the history
This is safer (we get a type error if a type is changed), and more
readable.

Enable @typescript-eslint/non-nullable-type-assertion-style to make
sure we don't introduce more of these.

Signed-off-by: Simon Ser <contact@emersion.fr>
  • Loading branch information
emersion committed Dec 20, 2024
1 parent 7582bdd commit bf0ab67
Show file tree
Hide file tree
Showing 17 changed files with 33 additions and 55 deletions.
1 change: 1 addition & 0 deletions front/.eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-unsafe-return": "error",
"@typescript-eslint/no-unsafe-call": "error",
"@typescript-eslint/non-nullable-type-assertion-style": "error",

"@typescript-eslint/ban-types": [
"error",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import type {
SpeedSectionPslEntity,
AvailableSwitchPositions,
SwitchPosition,
ApplicableTrackRange,
} from 'applications/editor/tools/rangeEdition/types';
import {
makeSpeedRestrictionTrackRanges,
Expand Down Expand Up @@ -158,7 +157,7 @@ const RangeEditionLeftPanel = () => {
true
);
if (returnedExtra) {
newRouteExtra[routeId] = last(trackRangesWithBothDirections) as ApplicableTrackRange;
newRouteExtra[routeId] = last(trackRangesWithBothDirections)!;
}
return trackRangesWithBothDirections;
});
Expand Down
4 changes: 2 additions & 2 deletions front/src/applications/editor/tools/rangeEdition/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export function getTrackRangeFeatures(
itemType: 'TrackRangeExtremity',
rangeIndex,
}),
point(last(track.geometry.coordinates) as Position, {
point(last(track.geometry.coordinates)!, {
...properties,
id: `speedSectionRangeExtremity::${rangeIndex}::${end}`,
track: range.track,
Expand Down Expand Up @@ -304,7 +304,7 @@ export function generatePslSignFeatures(
export function getPointAt(track: TrackSectionEntity, at: number): Position {
const dataLength = track.properties.length;
if (at <= 0) return track.geometry.coordinates[0];
if (at >= dataLength) return last(track.geometry.coordinates) as Position;
if (at >= dataLength) return last(track.geometry.coordinates)!;

const computedLength = length(track);
return along(track.geometry, (at * computedLength) / dataLength).geometry.coordinates;
Expand Down
4 changes: 2 additions & 2 deletions front/src/applications/editor/tools/routeEdition/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ export function computeRouteGeometry(
const isFirst = !i;
const isLast = i === trackRanges.length - 1;

const p1 = first(track.geometry.coordinates) as Position;
const p2 = last(track.geometry.coordinates) as Position;
const p1 = first(track.geometry.coordinates)!;
const p2 = last(track.geometry.coordinates)!;

// Weird case of only range:
if (isFirst && isLast) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useContext, useEffect, useMemo, useState } from 'react';

import { featureCollection, point } from '@turf/helpers';
import nearestPoint from '@turf/nearest-point';
import type { Position } from 'geojson';
import { first, last } from 'lodash';
import { useTranslation } from 'react-i18next';
import { Layer, Popup, Source } from 'react-map-gl/maplibre';
Expand Down Expand Up @@ -98,10 +97,7 @@ const SwitchEditionLayers = () => {
const trackSectionPoints = hoveredTrack.geometry.coordinates;
const closest = nearestPoint(
mousePosition,
featureCollection([
point(first(trackSectionPoints) as Position),
point(last(trackSectionPoints) as Position),
])
featureCollection([point(first(trackSectionPoints)!), point(last(trackSectionPoints)!)])
);

setState({
Expand Down
31 changes: 7 additions & 24 deletions front/src/applications/operationalStudies/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export const formatElectrificationRanges = (
// We know we will find one because currentProfile is still defined
const associatedProfile = electricalProfiles.find(
(profile) => profile.stop >= currentElectrification.stop
) as ElectricalRangesData<ElectricalProfileValue>;
)!;

return {
electrificationUsage: {
Expand All @@ -146,7 +146,7 @@ export const formatElectrificationRanges = (
// We know we will find one because theirs last stops are the same
const associatedProfile = electricalProfiles.find(
(profile) => profile.stop >= currentElectrification.stop
) as ElectricalRangesData<ElectricalProfileValue>;
)!;

return {
electrificationUsage: {
Expand All @@ -168,34 +168,17 @@ export const preparePathPropertiesData = (
trainSchedulePath: TrainScheduleResult['path'],
t: TFunction
): PathPropertiesFormatted => {
const formattedSlopes = transformBoundariesDataToPositionDataArray(
slopes as NonNullable<PathProperties['slopes']>,
length,
'gradient'
);

const formattedCurves = transformBoundariesDataToPositionDataArray(
curves as NonNullable<PathProperties['curves']>,
length,
'radius'
);

const electrificationsRanges = transformBoundariesDataToRangesData(
electrifications as NonNullable<PathProperties['electrifications']>,
length
);

const formattedSlopes = transformBoundariesDataToPositionDataArray(slopes!, length, 'gradient');
const formattedCurves = transformBoundariesDataToPositionDataArray(curves!, length, 'radius');
const electrificationsRanges = transformBoundariesDataToRangesData(electrifications!, length);
const electricalProfilesRanges = transformBoundariesDataToRangesData(electricalProfiles, length);

const electrificationRanges = formatElectrificationRanges(
electrificationsRanges,
electricalProfilesRanges
);

const voltageRanges = getPathVoltages(
electrifications as NonNullable<PathProperties['electrifications']>,
length
);
const voltageRanges = getPathVoltages(electrifications!, length);

const operationalPointsWithAllWaypoints = upsertMapWaypointsInOperationalPoints(
trainSchedulePath,
Expand All @@ -209,7 +192,7 @@ export const preparePathPropertiesData = (
curves: formattedCurves,
slopes: formattedSlopes,
operationalPoints: operationalPointsWithAllWaypoints,
geometry: geometry as NonNullable<PathProperties['geometry']>,
geometry: geometry!,
voltages: voltageRanges,
};
};
Expand Down
10 changes: 5 additions & 5 deletions front/src/common/Map/WarpedMap/SimulationWarpedMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import bbox from '@turf/bbox';
import { lineString } from '@turf/helpers';
import type { BBox2d } from '@turf/helpers/dist/js/lib/geojson';
import length from '@turf/length';
import type { Feature, FeatureCollection, LineString, Position } from 'geojson';
import type { Feature, FeatureCollection, LineString } from 'geojson';
import { clamp, first, isEmpty, isNil, last, mapValues, omitBy } from 'lodash';
import type { LngLatBoundsLike } from 'maplibre-gl';
import { PiLinkBold, PiLinkBreakBold } from 'react-icons/pi';
Expand Down Expand Up @@ -103,9 +103,9 @@ const SimulationWarpedMap = ({
const size = !rotate ? height : width;

// we don't clip the path
const transformedPath = transform(path, false) as typeof path;
const latStart = (first(transformedPath.geometry.coordinates) as Position)[1];
const latEnd = (last(transformedPath.geometry.coordinates) as Position)[1];
const transformedPath = transform(path, false)!;
const latStart = first(transformedPath.geometry.coordinates)![1];
const latEnd = last(transformedPath.geometry.coordinates)![1];

/*
* Here, `y` is the function provided by d3 to scale distance in meters from the beginning of the path to pixels
Expand Down Expand Up @@ -140,7 +140,7 @@ const SimulationWarpedMap = ({
[warpedBBox[0], latTop],
[warpedBBox[2], latBottom],
],
}) as typeof transformedPath;
})!;
const clippedPathBBox = bbox(clippedPath) as BBox2d;
const lngAverage = (clippedPathBBox[0] + clippedPathBBox[2]) / 2;

Expand Down
4 changes: 2 additions & 2 deletions front/src/common/Map/WarpedMap/core/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ export function getSamples(
const step = l / (samples - 1);
for (let i = 0; i < samples; i++) {
if (!i) {
points.push(point(first(line.geometry.coordinates) as Position));
points.push(point(first(line.geometry.coordinates)!));
} else if (i === samples - 1) {
points.push(point(last(line.geometry.coordinates) as Position));
points.push(point(last(line.geometry.coordinates)!));
} else {
points.push(along(line, step * i, { units: 'meters' }));
}
Expand Down
2 changes: 1 addition & 1 deletion front/src/common/Map/WarpedMap/core/quadtree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function getQuadTree<G extends Geometry | null = Geometry, P = GeoJsonPro
const candidate = candidates[k];
if (bboxIntersect(fBBox, candidate)) {
quad.children[k] = quad.children[k] || getNewQuadChild(candidate, d === depth - 1);
newQuads.push(quad.children[k] as QuadChild<Feature<G, P>>);
newQuads.push(quad.children[k]!);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions front/src/common/Selector/Selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const SelectorItem = <T extends string | null>({
updateData: (newData: { [key: string]: string }) => void;
};
}) => {
const inputValue = extraColumn?.data[item.id as string] || '';
const inputValue = extraColumn?.data[item.id!] || '';
const isDisabled = isDefaultItem || !extraColumn;
const isWarning = inputValue === '' && !isDisabled;

Expand Down Expand Up @@ -104,11 +104,11 @@ const SelectorItem = <T extends string | null>({
sm
noMargin
disabled={isDefaultItem}
value={isDefaultItem ? extraColumn.defaultValue : extraColumn.data[item.id as string]}
value={isDefaultItem ? extraColumn.defaultValue : extraColumn.data[item.id!]}
onChange={(e) =>
extraColumn.updateData({
...extraColumn.data,
[item.id as string]: e.target.value,
[item.id!]: e.target.value,
})
}
/>
Expand Down
2 changes: 1 addition & 1 deletion front/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ export default function Container() {
);
}

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<Container />);
6 changes: 2 additions & 4 deletions front/src/modules/rollingStock/helpers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ export const getDefaultRollingStockMode = (selectedMode: string | null): EffortC
: null;

const getDefaultMultiUnitsParameter = (parameter: string): MultiUnitsParameter => {
const { min, max, units } = RS_SCHEMA_PROPERTIES.find(
(rsParam) => rsParam.title === parameter
) as SchemaProperty;
const { min, max, units } = RS_SCHEMA_PROPERTIES.find((rsParam) => rsParam.title === parameter)!;
return {
min: min!,
max: max!,
Expand Down Expand Up @@ -157,7 +155,7 @@ export const rollingStockEditorQueryArg = (
comfort_acceleration: data.comfortAcceleration,
const_gamma: data.constGamma,
inertia_coefficient: data.inertiaCoefficient,
mass: handleUnitValue({ unit: 'kg', value: data.mass.value }, data.mass, data.mass) as number, // Back-end needs value in kg.
mass: handleUnitValue({ unit: 'kg', value: data.mass.value }, data.mass, data.mass)!, // Back-end needs value in kg.
rolling_resistance: {
A: handleUnitValue(
{ unit: 'N', value: data.rollingResistanceA.value },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const SimulationResultExport = ({
>
{({ url }) => (
<Button
onClick={() => window.open(url as string, '_blank')}
onClick={() => window.open(url!, '_blank')}
variant="Quiet"
label={t('simulationSheet')}
size="medium"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ const specificInterpolateOnTime =
const currentData = dataSimulation[listValue] as ObjectWithXAxis[];

if (currentData.length) {
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
const timeBisect = d3.bisector<ObjectWithXAxis, Time>((d) => d.time as Time).left;
const index = timeBisect(currentData, timePositionLocal, 1);
bisection = [currentData[index - 1], currentData[index]];
Expand Down
2 changes: 1 addition & 1 deletion front/src/modules/study/components/AddOrEditStudyModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ const AddOrEditStudyModal = ({ editionMode, study, scenarios }: AddOrEditStudyMo
label: t(`studyStates.${currentStudy.state}`).toString(),
}}
options={studyStateOptions}
onChange={(e) => handleStudyInputChange('state', e?.id as StudyForm['state'])}
onChange={(e) => handleStudyInputChange('state', e?.id)}
/>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion front/src/test-data/geojson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function lineString(
): Feature<LineString> {
if (typeof arg1 === 'number' || !arg1) {
const length = arg1 || random(2, 5, false);
const valueRange = (arg2 as [number, number]) || [random(), random()];
const valueRange = arg2 || [random(), random()];
const positions = Array.from({ length }).map(() => position(valueRange));
return turfLineString(positions);
}
Expand Down
2 changes: 1 addition & 1 deletion front/src/utils/timeManipulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function sec2time(sec: number) {
}

export function sec2datetime(sec: number) {
return d3.timeParse('%H:%M:%S')(sec2time(sec)) as Date; // We consider it's utc to avoid +0 delta
return d3.timeParse('%H:%M:%S')(sec2time(sec))!; // We consider it's utc to avoid +0 delta
}

/**
Expand Down

0 comments on commit bf0ab67

Please sign in to comment.