Skip to content

Commit

Permalink
Fix anys
Browse files Browse the repository at this point in the history
And non-null assertions
  • Loading branch information
RoyEJohnson committed Jan 8, 2025
1 parent 7c94e2c commit 9fe5034
Show file tree
Hide file tree
Showing 43 changed files with 157 additions and 106 deletions.
1 change: 1 addition & 0 deletions src/app/components/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const applyColor = (color: ColorSet) => `
type Variant = 'primary' | 'secondary' | 'transparent' | 'default';
type Size = 'large' | 'medium' | 'small';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ComponentType = keyof JSX.IntrinsicElements | React.JSXElementConstructor<any>;

interface ButtonProps<T extends ComponentType | undefined> {
Expand Down
1 change: 1 addition & 0 deletions src/app/components/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import theme, { defaultFocusOutline } from '../theme';
import { preventDefault } from '../utils';
import { textStyle } from './Typography/base';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ComponentWithRef = React.ComponentType<{ref: React.RefObject<any>}>;
interface ToggleProps<T extends ComponentWithRef = ComponentWithRef> {
className?: string;
Expand Down
2 changes: 1 addition & 1 deletion src/app/components/GoToTopButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const GoToTopIcon = styled(AngleUp)`
interface GoToTopButtonProps {
i18nAriaLabel: string;
onClick: () => void;
[key: string]: any;
[key: string]: unknown;
}

// tslint:disable-next-line: variable-name
Expand Down
4 changes: 2 additions & 2 deletions src/app/components/htmlMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React, { ComponentType, HTMLAttributes } from 'react';
import { useIntl } from 'react-intl';

// tslint:disable-next-line:variable-name
type Type = <T extends any>(messageKey: string, Component: ComponentType<HTMLAttributes<T>>) =>
ComponentType<{values?: Record<string, any>} & HTMLAttributes<T>>;
type Type = <T extends object>(messageKey: string, Component: ComponentType<HTMLAttributes<T>>) =>
ComponentType<{values?: Record<string, Date | string | number | null>} & HTMLAttributes<T>>;

// tslint:disable-next-line:variable-name
export const htmlMessage: Type = (messageKey, Component) => ({values, ...props}) =>
Expand Down
3 changes: 2 additions & 1 deletion src/app/content/components/Assigned.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ const StyledButton = styled(Button)`
`;

// Override layout for Toast
const assignedMobileTop = (props: any) => getMobileSearchFailureTop(props) - bookBannerMobileMiniHeight;
const assignedMobileTop = (props: {mobileToolbarOpen: boolean}) =>
getMobileSearchFailureTop(props) - bookBannerMobileMiniHeight;
// tslint:disable-next-line: variable-name
const ToastOverride = styled(PageToasts)`
top: ${topbarDesktopHeight}rem;
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/components/AssignedTopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const useTextResizeIntegration = (handleChange: (value: TextResizerValue) => voi
const win = window;
const referrer = new URL(win.document.referrer);

const handler = (event: MessageEvent<any>) => {
const handler = (event: MessageEvent) => {
if (
event.data.type === 'TextSizeUpdate' &&
event.origin === referrer.origin &&
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/components/Page/connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export interface PagePropTypes {
systemQueryParams: SystemQueryParams;
textSize: TextResizerValue;
lockNavigation: boolean;
ToastOverride: StyledComponent<'div', any, {}, never>;
ToastOverride: StyledComponent<'div', object, {}, never>;
topHeadingLevel?: number;
}

Expand Down
3 changes: 2 additions & 1 deletion src/app/content/components/Topbar/TextResizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FormattedMessage } from 'react-intl';
import decreaseTextSizeIcon from '../../../../assets/text-size-decrease.svg';
import increaseTextSizeIcon from '../../../../assets/text-size-increase.svg';
import textSizeIcon from '../../../../assets/text-size.svg';
import { HTMLInputElement } from '@openstax/types/lib.dom';
import {
textResizerDefaultValue,
textResizerMaxValue,
Expand All @@ -23,7 +24,7 @@ export interface TextResizerProps {
// tslint:disable-next-line:variable-name
export const TextResizer = (props: TextResizerProps) => {
const onChangeTextSize = (e: React.FormEvent<HTMLInputElement>) => {
const target = (e as any).currentTarget;
const target = e.currentTarget;
const value = parseInt(target.value, 10) as TextResizerValue;
if (!textResizerValues.includes(value)) { return; }
props.setTextSize(value);
Expand Down
4 changes: 3 additions & 1 deletion src/app/content/highlights/components/ShowMyHighlights.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import Highlights from './Highlights';
import HighlightsToasts from './HighlightsToasts';
import * as Styled from './ShowMyHighlightsStyles';
import Filters from './SummaryPopup/Filters';
import { ServiceConsumer } from '../../../context/Services';

interface ShowMyHighlightsProps {
authenticated: User | undefined;
Expand Down Expand Up @@ -119,4 +120,5 @@ const connector = connect(
})
);

export default flow(withServices, connector)(ShowMyHighlights as React.ComponentType<any>);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default flow(withServices, connector)(ShowMyHighlights as unknown as React.ComponentType<ServiceConsumer>);
5 changes: 3 additions & 2 deletions src/app/content/highlights/components/cardUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,11 @@ const updateStackedCardsPositions = (
const marginToAdd = index > 0 || addAditionalMarginForTheFirstCard ? remsToPx(cardMarginBottom) : 0;
const lastVisibleCardBottom = lastVisibleCardPosition + lastVisibleCardHeight;
const stackedTopOffset = Math.max(topOffset, lastVisibleCardBottom + marginToAdd);
const heightsForId = heights.get(highlight.id);

if (heights.get(highlight.id) && !checkIfHiddenByCollapsedAncestor(highlight)) {
if (heightsForId && !checkIfHiddenByCollapsedAncestor(highlight)) {
lastVisibleCardPosition = stackedTopOffset;
lastVisibleCardHeight = heights.get(highlight.id)!;
lastVisibleCardHeight = heightsForId;
}

positions.set(highlight.id, stackedTopOffset);
Expand Down
4 changes: 2 additions & 2 deletions src/app/content/highlights/components/utils/onClickOutside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ export const useOnClickOutside = (

export default onClickOutside;

const isRefWithHtmlElement = (el: any): el is React.RefObject<HTMLElement> => {
const isRefWithHtmlElement = (el: {current?: unknown}): el is React.RefObject<HTMLElement> => {
return el instanceof Object && isHtmlElement(el.current);
};

export const isElementForOnClickOutside = (el: any): el is HTMLElement | React.RefObject<HTMLElement> => {
export const isElementForOnClickOutside = (el: object): el is HTMLElement | React.RefObject<HTMLElement> => {
return isHtmlElement(el) || isRefWithHtmlElement(el);
};
10 changes: 8 additions & 2 deletions src/app/content/highlights/utils/selectorsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ export const getLoadedCountsPerSource = (sources: SummaryHighlights | null) => f
mapValues(size)
)(sources);

export const checkIfHasMoreResults = (loaded: any, filteredCounts: any, pagination: SummaryHighlightsPagination) => {
return !!(pagination || Object.keys(omit(Object.keys(loaded), filteredCounts)).length);
export const checkIfHasMoreResults = (
loaded: object,
filteredCounts: object,
pagination: SummaryHighlightsPagination
) => {
return !!(
pagination || Object.keys(omit(Object.keys(loaded), filteredCounts)).length
);
};
8 changes: 6 additions & 2 deletions src/app/content/highlights/utils/summaryHighlightsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,16 @@ export const removeFromTotalCounts = (
totalCounts: CountsPerSource,
highlight: HighlightData
) => {
if (totalCounts[highlight.sourceId] && totalCounts[highlight.sourceId][highlight.color]) {
// Type issue: totalCounts does not allow members to be undefined,
// but in practice they are
const tc = totalCounts[highlight.sourceId]?.[highlight.color];

if (tc) {
const newTotal = {
...totalCounts,
[highlight.sourceId]: {
...totalCounts[highlight.sourceId],
[highlight.color]: totalCounts[highlight.sourceId][highlight.color]! - 1,
[highlight.color]: tc - 1,
},
};

Expand Down
3 changes: 2 additions & 1 deletion src/app/content/hooks/registerPageView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import googleAnalyticsClient from '../../../gateways/googleAnalyticsClient';
import * as selectNavigation from '../../navigation/selectors';
import { AnyRoute, RouteHookBody } from '../../navigation/types';
import { AppServices, MiddlewareAPI } from '../../types';
import { OutputParams } from 'query-string';

export const hookBody: RouteHookBody<AnyRoute> = (services: MiddlewareAPI & AppServices) => {
let lastTrackedLocation: any;
let lastTrackedLocation: { query: OutputParams; pathname: string; };

return async(action) => {
const state = services.getState();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import * as ksSelectors from '../selectors';
import ShowKeyboardShortcuts from './ShowKeyboardShortcuts';

// tslint:disable-next-line:variable-name
const StyledModal = styled<any /* there is a bug in the styled-components types when using forwardRef */>(Modal)`
const StyledModal = styled(Modal)`
max-width: 92.8rem;
`;

Expand Down
2 changes: 1 addition & 1 deletion src/app/content/studyGuides/hooks/openStudyGuides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const hookBody: ActionHookBody<typeof openStudyGuides> = (services) => as

if (loggedOutAndQueryMissingFirstChapter || (!notLoggedIn && defaultFilter)) {
services.dispatch(replace(match as AnyMatch, {
search: getQueryForParam(summaryFilters as any as Record<string, string[]>, query),
search: getQueryForParam(summaryFilters as unknown as Record<string, string[]>, query),
}));
} else {
const studyGuides = select.summaryStudyGuides(state);
Expand Down
2 changes: 1 addition & 1 deletion src/app/content/studyGuides/hooks/printStudyGuides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const asyncHelper = async(services: MiddlewareAPI & AppServices) => {

try {
response = await loadMore(services);
} catch (error: any) {
} catch (error: unknown) {
services.dispatch(toggleStudyGuidesSummaryLoading(false));
throw ensureApplicationErrorType(error, new StudyGuidesPopupPrintError({ destination: 'studyGuides' }));
}
Expand Down
25 changes: 18 additions & 7 deletions src/app/content/studyGuides/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,29 @@ export const getFiltersFromQuery = (query: OutputParams) => {
return { colors, locationIds };
};

export const updateQueryFromFilterChange = (dispatch: Dispatch, state: AppState, change: SummaryFiltersUpdate) => {
const updatedFilters: {[key: string]: any} = updateSummaryFilters(selectors.summaryFilters(state), change);
export const updateQueryFromFilterChange = (
dispatch: Dispatch,
state: AppState,
change: SummaryFiltersUpdate
) => {
const updatedFilters = updateSummaryFilters(
selectors.summaryFilters(state),
change
) as unknown as Parameters<typeof getQueryForParam>[0];
// convert empty filter arrys to null so they are preserved in query
for (const filter in updatedFilters) {
if (updatedFilters[filter] && !updatedFilters[filter].length) {
if (updatedFilters[filter] && !updatedFilters[filter]?.length) {
updatedFilters[filter] = null;
}
}
const match = navigation.match(state);
const existingQuery = navigation.query(state);
if (!match ) { return; }
dispatch(replace(match, {
search: getQueryForParam(updatedFilters as any as Record<string, string[]>, existingQuery),
}));
if (!match) {
return;
}
dispatch(
replace(match, {
search: getQueryForParam(updatedFilters, existingQuery),
})
);
};
8 changes: 4 additions & 4 deletions src/app/content/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const parseContents = (book: ArchiveBook, contents: Array<ArchiveTree | A
return contents;
};

const pickArchiveFields = (archiveBook: VersionedArchiveBookWithConfig) => ({
const pickArchiveFields = (archiveBook: VersionedArchiveBookWithConfig): VersionedArchiveBookWithConfig => ({
archiveVersion: archiveBook.archiveVersion,
contentVersion: archiveBook.contentVersion,
id: archiveBook.id,
Expand All @@ -100,7 +100,8 @@ export const formatBookData = <O extends OSWebBook | undefined>(
): O extends OSWebBook ? BookWithOSWebData : VersionedArchiveBookWithConfig => {
if (osWebBook === undefined) {
// as any necessary https://github.com/Microsoft/TypeScript/issues/13995
return pickArchiveFields(archiveBook) as VersionedArchiveBookWithConfig as any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return pickArchiveFields(archiveBook) as any;
}
return {
...pickArchiveFields(archiveBook),
Expand All @@ -116,8 +117,7 @@ export const formatBookData = <O extends OSWebBook | undefined>(
subject: osWebBook.book_subjects[0]?.subject_name,
subjects: osWebBook.book_subjects,
theme: osWebBook.cover_color,
// as any necessary https://github.com/Microsoft/TypeScript/issues/13995
} as BookWithOSWebData as any;
} as BookWithOSWebData;
};

export const makeUnifiedBookLoader = (
Expand Down
9 changes: 6 additions & 3 deletions src/app/content/utils/domUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { HTMLDetailsElement, HTMLElement, MouseEvent } from '@openstax/types/lib.dom';
import React from 'react';

if (typeof(document) !== 'undefined') {
import(/* webpackChunkName: "Node.children" */ 'mdn-polyfills/Node.prototype.children');
Expand Down Expand Up @@ -99,9 +100,11 @@ export const setSidebarHeight = (sidebar: HTMLElement, window: Window) => {
};
};

export const fixSafariScrolling = (event: any) => {
event.target.style.overflowY = 'hidden';
setTimeout(() => { event.target.style.overflowY = 'auto'; });
export const fixSafariScrolling = (event: Event) => {
const target = event.target as HTMLElement;

target.style.overflowY = 'hidden';
setTimeout(() => { target.style.overflowY = 'auto'; });
};

export const isClickWithModifierKeys = (e: React.MouseEvent | MouseEvent) =>
Expand Down
2 changes: 1 addition & 1 deletion src/app/context/Services.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export {
Provider,
};

interface ServiceConsumer {
export interface ServiceConsumer {
services: AppServices & MiddlewareAPI;
}

Expand Down
1 change: 1 addition & 0 deletions src/app/developer/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const developerHome: Route = {
loader: () => import(/* webpackChunkName: "route-developer-home" */ './components/Home'),
loading: () => null,
modules: ['route-developer-home'],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
webpack: /* istanbul ignore next */ () => [(require as any).resolveWeak('./components/Home')],
}),
getUrl: (): string => pathToRegexp.compile(ROUTES_PATH)(),
Expand Down
1 change: 1 addition & 0 deletions src/app/domUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export const findFirstAncestorOrSelfOfType =

export const findFirstAncestorOrSelf = <T = HTMLElement>(
node: Node,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
predicate: ((e: any) => boolean) | ((e: any) => e is T)
): T | void => {
if (isHtmlElement(node) && predicate(node)) {
Expand Down
1 change: 1 addition & 0 deletions src/app/errors/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const loadableArgs = {
loader: () => import(/* webpackChunkName: "LoaderCentered" */ './components/LoaderCentered'),
loading: () => null,
modules: ['LoaderCentered'],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
webpack: /* istanbul ignore next */ () => [(require as any).resolveWeak('./components/LoaderCentered')],
};

Expand Down
8 changes: 4 additions & 4 deletions src/app/fpUtils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { FirstArgumentType } from './types';

export const and = <A extends any[]>(...predicates: Array<(...args: A) => boolean>) => (...args: A) =>
export const and = <A extends unknown[]>(...predicates: Array<(...args: A) => boolean>) => (...args: A) =>
predicates.reduce((result, predicate) => result && predicate(...args), true);

export const or = <A extends any[]>(...predicates: Array<(...args: A) => boolean>) => (...args: A) =>
export const or = <A extends unknown[]>(...predicates: Array<(...args: A) => boolean>) => (...args: A) =>
predicates.reduce((result, predicate) => result || predicate(...args), false);

export const ifUndefined = <I, D>(item: I | undefined, defaultValue: D): I | D =>
Expand All @@ -12,13 +12,13 @@ export const ifUndefined = <I, D>(item: I | undefined, defaultValue: D): I | D
/*
* returns a function that inverts the result of the passed in function
*/
export const not = <A extends any[]>(wrapped: (...args: A) => any) => (...args: A) => !wrapped(...args);
export const not = <A extends unknown[]>(wrapped: (...args: A) => unknown) => (...args: A) => !wrapped(...args);

/*
* returns a function that evaluates its argument against the given predicate
*/
// tslint:disable-next-line:ban-types
export const match = <T extends any>(predicate: T) => (arg: T extends Function ? FirstArgumentType<T> : T) => {
export const match = <T extends unknown>(predicate: T) => (arg: T extends Function ? FirstArgumentType<T> : T) => {
if (typeof predicate === 'function') {
return !!predicate(arg);
}
Expand Down
Loading

0 comments on commit 9fe5034

Please sign in to comment.