Skip to content

Commit

Permalink
first round of updates to disable type assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
rsun19 committed Jun 5, 2024
1 parent 74c6869 commit 4ac45ef
Show file tree
Hide file tree
Showing 29 changed files with 156 additions and 101 deletions.
7 changes: 3 additions & 4 deletions frontend/src/__tests__/unit/testUtils/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ export const renderHook = <
options?: RenderHookOptions<Props, Q, Container, BaseElement>,
): RenderHookResultExt<Result, Props> => {
let updateCount = 0;
let prevResult: Result | undefined;
let currentResult: Result | undefined;
let prevResult: Result;
let currentResult: Result;

const renderResult = renderHookRTL((props) => {
updateCount++;
Expand All @@ -80,8 +80,7 @@ export const renderHook = <
const renderResultExt: RenderHookResultExt<Result, Props> = {
...renderResult,

getPreviousResult: () =>
updateCount > 1 ? (prevResult as Result) : renderResult.result.current,
getPreviousResult: () => (updateCount > 1 ? prevResult : renderResult.result.current),

getUpdateCount: () => updateCount,

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/api/errorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { K8sStatus } from '@openshift/dynamic-plugin-sdk-utils';
import { AxiosError } from 'axios';

export const isK8sStatus = (data: unknown): data is K8sStatus =>
(data as K8sStatus).kind === 'Status';
typeof data === 'object' && data !== null && 'kind' in data && data.kind === 'Status';

export class K8sStatusError extends Error {
public statusObject: K8sStatus;
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/api/modelRegistry/errorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ModelRegistryError } from '~/concepts/modelRegistry/types';
import { isCommonStateError } from '~/utilities/useFetchState';

const isError = (e: unknown): e is ModelRegistryError =>
['code', 'message'].every((key) => key in (e as ModelRegistryError));
typeof e === 'object' && e !== null && ['code', 'message'].every((key) => key in e);

export const handleModelRegistryFailures = <T>(promise: Promise<T>): Promise<T> =>
promise
Expand Down
6 changes: 4 additions & 2 deletions frontend/src/api/pipelines/errorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ type ResultErrorKF = {
};

const isErrorKF = (e: unknown): e is ErrorKF =>
['error', 'code', 'message'].every((key) => key in (e as ErrorKF));
typeof e === 'object' && e !== null && ['error', 'code', 'message'].every((key) => key in e);

const isErrorDetailsKF = (result: unknown): result is ResultErrorKF =>
['error_details', 'error_message'].every((key) => key in (result as ResultErrorKF));
typeof result === 'object' &&
result !== null &&
['error_details', 'error_message'].every((key) => key in result);

export const handlePipelineFailures = <T>(promise: Promise<T>): Promise<T> =>
promise
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/api/trustyai/errorUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ type TrustyAIClientErrorViolation = {
};

const isTrustyAIClientError = (e: unknown): e is TrustyAIClientError =>
typeof e === 'object' &&
['title', 'status', 'violations'].every((key) => key in (e as TrustyAIClientError));
typeof e === 'object' && e !== null && ['title', 'status', 'violations'].every((key) => key in e);

export const handleTrustyAIFailures = <T>(promise: Promise<T>): Promise<T> =>
promise.then((result) => {
Expand Down
63 changes: 33 additions & 30 deletions frontend/src/components/DocCardBadges.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { QuickStartContext, QuickStartContextValues } from '@patternfly/quicksta
import { OdhDocument, OdhDocumentType } from '~/types';
import { getQuickStartCompletionStatus, CompletionStatusEnum } from '~/utilities/quickStartUtils';
import { DOC_TYPE_TOOLTIPS } from '~/utilities/const';
import { getLabelColorForDocType, getDuration } from '~/utilities/utils';
import { getLabelColorForDocType, getDuration, asEnumMember } from '~/utilities/utils';
import { DOC_TYPE_LABEL } from '~/pages/learningCenter/const';

import './OdhCard.scss';
Expand All @@ -19,7 +19,7 @@ const DocCardBadges: React.FC<DocCardBadgesProps> = ({ odhDoc }) => {
const [completionStatus, setCompletionStatus] = React.useState<
CompletionStatusEnum | undefined
>();
const docType = odhDoc.spec.type as OdhDocumentType;
const docType = asEnumMember(odhDoc.spec.type, OdhDocumentType);
const docName = odhDoc.metadata.name;
const duration = odhDoc.spec.durationMinutes;

Expand All @@ -32,35 +32,38 @@ const DocCardBadges: React.FC<DocCardBadgesProps> = ({ odhDoc }) => {
}
}, [qsContext, docType, docName]);

const label = DOC_TYPE_LABEL[docType] || 'Documentation';
if (docType !== null) {
const label = DOC_TYPE_LABEL[docType] || 'Documentation';

return (
<LabelGroup defaultIsOpen numLabels={3}>
<Tooltip content={DOC_TYPE_TOOLTIPS[docType]}>
<Label color={getLabelColorForDocType(docType)}>{label}</Label>
</Tooltip>
{duration ? (
<Label variant="outline" color="grey">
{getDuration(duration)}
</Label>
) : null}
{completionStatus === CompletionStatusEnum.InProgress ? (
<Label variant="outline" color="purple" icon={<SyncAltIcon />}>
In Progress
</Label>
) : null}
{completionStatus === CompletionStatusEnum.Success ? (
<Label variant="outline" color="green" icon={<CheckCircleIcon />}>
Complete
</Label>
) : null}
{completionStatus === CompletionStatusEnum.Failed ? (
<Label variant="outline" color="red" icon={<ExclamationCircleIcon />}>
Failed
</Label>
) : null}
</LabelGroup>
);
return (
<LabelGroup defaultIsOpen numLabels={3}>
<Tooltip content={DOC_TYPE_TOOLTIPS[docType]}>
<Label color={getLabelColorForDocType(docType)}>{label}</Label>
</Tooltip>
{duration ? (
<Label variant="outline" color="grey">
{getDuration(duration)}
</Label>
) : null}
{completionStatus === CompletionStatusEnum.InProgress ? (
<Label variant="outline" color="purple" icon={<SyncAltIcon />}>
In Progress
</Label>
) : null}
{completionStatus === CompletionStatusEnum.Success ? (
<Label variant="outline" color="green" icon={<CheckCircleIcon />}>
Complete
</Label>
) : null}
{completionStatus === CompletionStatusEnum.Failed ? (
<Label variant="outline" color="red" icon={<ExclamationCircleIcon />}>
Failed
</Label>
) : null}
</LabelGroup>
);
}
return null;
};

export default DocCardBadges;
29 changes: 16 additions & 13 deletions frontend/src/components/OdhDocListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ExternalLinkAltIcon } from '@patternfly/react-icons';
import { OdhDocument, OdhDocumentType } from '~/types';
import { getQuickStartLabel, launchQuickStart } from '~/utilities/quickStartUtils';
import { DOC_TYPE_TOOLTIPS } from '~/utilities/const';
import { getDuration } from '~/utilities/utils';
import { asEnumMember, getDuration } from '~/utilities/utils';
import { useQuickStartCardSelected } from './useQuickStartCardSelected';
import FavoriteButton from './FavoriteButton';

Expand All @@ -26,18 +26,21 @@ const OdhDocListItem: React.FC<OdhDocCardProps> = ({ odhDoc, favorite, updateFav
};

const renderTypeBadge = () => {
const docType = odhDoc.spec.type as OdhDocumentType;
const typeBadgeClasses = classNames('odh-list-item__partner-badge odh-m-doc', {
'odh-m-documentation': docType === OdhDocumentType.Documentation,
'odh-m-tutorial': docType === OdhDocumentType.Tutorial,
'odh-m-quick-start': docType === OdhDocumentType.QuickStart,
'odh-m-how-to': docType === OdhDocumentType.HowTo,
});
return (
<Tooltip content={DOC_TYPE_TOOLTIPS[docType]}>
<div className={typeBadgeClasses}>{odhDoc.spec.type}</div>
</Tooltip>
);
const docType = asEnumMember(odhDoc.spec.type, OdhDocumentType);
if (docType !== null) {
const typeBadgeClasses = classNames('odh-list-item__partner-badge odh-m-doc', {
'odh-m-documentation': docType === OdhDocumentType.Documentation,
'odh-m-tutorial': docType === OdhDocumentType.Tutorial,
'odh-m-quick-start': docType === OdhDocumentType.QuickStart,
'odh-m-how-to': docType === OdhDocumentType.HowTo,
});
return (
<Tooltip content={DOC_TYPE_TOOLTIPS[docType]}>
<div className={typeBadgeClasses}>{odhDoc.spec.type}</div>
</Tooltip>
);
}
return null;
};

const renderDocLink = () => {
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/ToastNotification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Alert, AlertActionCloseButton, AlertVariant } from '@patternfly/react-c
import { AppNotification } from '~/redux/types';
import { ackNotification, hideNotification } from '~/redux/actions/actions';
import { useAppDispatch } from '~/redux/hooks';
import { isEnumMember } from '~/utilities/utils';

const TOAST_NOTIFICATION_TIMEOUT = 8 * 1000;

Expand Down Expand Up @@ -36,7 +37,7 @@ const ToastNotification: React.FC<ToastNotificationProps> = ({ notification }) =

return (
<Alert
variant={notification.status as AlertVariant}
variant={isEnumMember(notification.status, AlertVariant) ? notification.status : undefined}
title={notification.title}
actionClose={
<AlertActionCloseButton onClose={() => dispatch(ackNotification(notification))} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { JavaScriptValue } from 'google-protobuf/google/protobuf/struct_pb';
import { ROCCurveConfig } from '~/concepts/pipelines/content/artifacts/charts/ROCCurve';
import { ConfidenceMetric } from './types';

export const isConfidenceMetric = (obj: JavaScriptValue): obj is ConfidenceMetric => {
const metric = obj as ConfidenceMetric;
return (
typeof metric.confidenceThreshold === 'number' &&
typeof metric.falsePositiveRate === 'number' &&
typeof metric.recall === 'number'
);
};
export const isConfidenceMetric = (obj: JavaScriptValue): obj is ConfidenceMetric =>
typeof obj === 'object' &&
obj !== null &&
'confidenceThreshold' in obj &&
'falsePositiveRate' in obj &&
'recall' in obj &&
obj.confidenceThreshold === 'number' &&
obj.falsePositiveRate === 'number' &&
obj.recall === 'number';

export const buildRocCurveConfig = (
confidenceMetricsArray: ConfidenceMetric[],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createPipelinesCR, deleteSecret } from '~/api';
import useDataConnections from '~/pages/projects/screens/detail/data-connections/useDataConnections';
import { EMPTY_AWS_PIPELINE_DATA } from '~/pages/projects/dataConnections/const';
import DashboardModalFooter from '~/concepts/dashboard/DashboardModalFooter';
import { asEnumMember } from '~/utilities/utils';
import { PipelinesDatabaseSection } from './PipelinesDatabaseSection';
import { ObjectStorageSection } from './ObjectStorageSection';
import {
Expand Down Expand Up @@ -48,7 +49,7 @@ export const ConfigurePipelinesServerModal: React.FC<ConfigurePipelinesServerMod
: config.database.value.every(({ key, value }) =>
DATABASE_CONNECTION_FIELDS.filter((field) => field.isRequired)
.map((field) => field.key)
.includes(key as DatabaseConnectionKeys)
.includes(asEnumMember(key, DatabaseConnectionKeys)!)
? !!value
: true,
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,11 @@ export const AcceleratorIdentifierMultiselect: React.FC<AcceleratorIdentifierMul
id="multi-create-typeahead-select"
isOpen={isOpen}
selected={data}
onSelect={(ev, selection) => onSelect(selection as string)}
onSelect={(ev, selection) => {
if (typeof selection === 'string') {
onSelect(selection);
}
}}
onOpenChange={() => setIsOpen(false)}
toggle={toggle}
>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/pages/learningCenter/LearningCenterToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ const LearningCenterToolbar: React.FC<LearningCenterToolbarProps> = ({
const onSortTypeSelect = React.useCallback(
(e: React.MouseEvent | React.ChangeEvent) => {
setIsSortTypeDropdownOpen(false);
const selection = (e.target as Element).getAttribute('data-key') ?? '';
const selection = e.target instanceof Element ? e.target.getAttribute('data-key') ?? '' : '';
setQueryArgument(navigate, DOC_SORT_KEY, selection);
},
[navigate],
Expand All @@ -133,7 +133,7 @@ const LearningCenterToolbar: React.FC<LearningCenterToolbarProps> = ({
const onSortOrderSelect = React.useCallback(
(e: React.MouseEvent | React.ChangeEvent) => {
setIsSortOrderDropdownOpen(false);
const selection = (e.target as Element).getAttribute('data-key') ?? '';
const selection = e.target instanceof Element ? e.target.getAttribute('data-key') ?? '' : '';
setQueryArgument(navigate, DOC_SORT_ORDER_KEY, selection);
},
[navigate],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@ const ModelVersionSelector: React.FC<ModelVersionSelectorProps> = ({
const menu = (
<Menu
onSelect={(_e, itemId) => {
onSelect(itemId as string);
setOpen(false);
if (typeof itemId === 'string') {
onSelect(itemId);
setOpen(false);
}
}}
data-id="model-version-selector-menu"
ref={menuRef}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import EmptyModelRegistryState from '~/pages/modelRegistry/screens/components/Em
import { filterModelVersions } from '~/pages/modelRegistry/screens/utils';
import { ModelRegistrySelectorContext } from '~/concepts/modelRegistry/context/ModelRegistrySelectorContext';
import { modelVersionArchiveUrl } from '~/pages/modelRegistry/screens/routeUtils';
import { isEnumMember } from '~/utilities/utils';
import ModelVersionsTable from './ModelVersionsTable';

type ModelVersionListViewProps = {
Expand Down Expand Up @@ -89,7 +90,9 @@ const ModelVersionListView: React.FC<ModelVersionListViewProps> = ({
}))}
value={searchType}
onChange={(newSearchType) => {
setSearchType(newSearchType as SearchType);
if (isEnumMember(newSearchType, SearchType)) {
setSearchType(newSearchType);
}
}}
icon={<FilterIcon />}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { ModelVersion } from '~/concepts/modelRegistry/types';
import SimpleDropdownSelect from '~/components/SimpleDropdownSelect';
import { filterModelVersions } from '~/pages/modelRegistry/screens/utils';
import EmptyModelRegistryState from '~/pages/modelRegistry/screens/components/EmptyModelRegistryState';
import { isEnumMember } from '~/utilities/utils';
import ModelVersionsArchiveTable from './ModelVersionsArchiveTable';

type ModelVersionsArchiveListViewProps = {
Expand Down Expand Up @@ -63,7 +64,9 @@ const ModelVersionsArchiveListView: React.FC<ModelVersionsArchiveListViewProps>
}))}
value={searchType}
onChange={(newSearchType) => {
setSearchType(newSearchType as SearchType);
if (isEnumMember(newSearchType, SearchType)) {
setSearchType(newSearchType);
}
}}
icon={<FilterIcon />}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { filterRegisteredModels } from '~/pages/modelRegistry/screens/utils';
import { ModelRegistrySelectorContext } from '~/concepts/modelRegistry/context/ModelRegistrySelectorContext';
import EmptyModelRegistryState from '~/pages/modelRegistry/screens/components/EmptyModelRegistryState';
import { registeredModelArchiveUrl } from '~/pages/modelRegistry/screens/routeUtils';
import { isEnumMember } from '~/utilities/utils';
import RegisteredModelTable from './RegisteredModelTable';
import RegisteredModelsTableToolbar from './RegisteredModelsTableToolbar';

Expand Down Expand Up @@ -71,7 +72,9 @@ const RegisteredModelListView: React.FC<RegisteredModelListViewProps> = ({
}))}
value={searchType}
onChange={(newSearchType) => {
setSearchType(newSearchType as SearchType);
if (isEnumMember(newSearchType, SearchType)) {
setSearchType(newSearchType);
}
}}
icon={<FilterIcon />}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { RegisteredModel } from '~/concepts/modelRegistry/types';
import SimpleDropdownSelect from '~/components/SimpleDropdownSelect';
import { filterRegisteredModels } from '~/pages/modelRegistry/screens/utils';
import EmptyModelRegistryState from '~/pages/modelRegistry/screens/components/EmptyModelRegistryState';
import { isEnumMember } from '~/utilities/utils';
import RegisteredModelsArchiveTable from './RegisteredModelsArchiveTable';

type RegisteredModelsArchiveListViewProps = {
Expand Down Expand Up @@ -68,7 +69,9 @@ const RegisteredModelsArchiveListView: React.FC<RegisteredModelsArchiveListViewP
}))}
value={searchType}
onChange={(newSearchType) => {
setSearchType(newSearchType as SearchType);
if (isEnumMember(newSearchType, SearchType)) {
setSearchType(newSearchType);
}
}}
icon={<FilterIcon />}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react';
import { FormGroup } from '@patternfly/react-core';
import { ServingRuntimeAPIProtocol, ServingRuntimePlatform } from '~/types';
import SimpleDropdownSelect from '~/components/SimpleDropdownSelect';
import { isEnumMember } from '~/utilities/utils';

type CustomServingRuntimeAPIProtocolSelectorProps = {
selectedAPIProtocol: ServingRuntimeAPIProtocol | undefined;
Expand Down Expand Up @@ -50,7 +51,9 @@ const CustomServingRuntimeAPIProtocolSelector: React.FC<
isDisabled={isOnlyModelMesh}
options={options}
value={selectedAPIProtocol || ''}
onChange={(key) => setSelectedAPIProtocol(key as ServingRuntimeAPIProtocol)}
onChange={(key) =>
isEnumMember(key, ServingRuntimeAPIProtocol) ? setSelectedAPIProtocol(key) : null
}
/>
</FormGroup>
);
Expand Down
Loading

0 comments on commit 4ac45ef

Please sign in to comment.