Skip to content

Commit

Permalink
Fix typescript errors
Browse files Browse the repository at this point in the history
  • Loading branch information
langdal committed Mar 31, 2022
1 parent 4a7f64b commit 4ce7165
Show file tree
Hide file tree
Showing 18 changed files with 52 additions and 60 deletions.
12 changes: 7 additions & 5 deletions components/home/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ export default function Home() {
message: 'Drag file here',
isError: false,
})
const [tempExperiment, setTempExperiment] = useState<ExperimentType>()
const [tempExperiment, setTempExperiment] = useState<
ExperimentType | undefined
>()

const saveExperimentLocally = useCallback(
(experiment: ExperimentType) => {
Expand Down Expand Up @@ -79,7 +81,7 @@ export default function Home() {
}

const load = (reader: FileReader) => {
const binaryResult: string | ArrayBuffer = reader.result
const binaryResult: string | ArrayBuffer | null = reader.result
try {
const experiment: ExperimentType = JSON.parse(binaryResult as string)
if (experiment.id === undefined) {
Expand Down Expand Up @@ -125,7 +127,7 @@ export default function Home() {

const getExperimentName = (key: string) => {
try {
const json: any = JSON.parse(localStorage.getItem(key))
const json: any = JSON.parse(localStorage.getItem(key) ?? '')
const experiment: ExperimentType = json.experiment
return !isEmpty(experiment.info.name) ? experiment.info.name : '-'
} catch (e) {
Expand All @@ -151,12 +153,12 @@ export default function Home() {
}

const handleOverwriteDialog = () => {
saveExperimentLocally(tempExperiment)
tempExperiment && saveExperimentLocally(tempExperiment)
setTempExperiment(undefined)
}

const handleCreateDialog = () => {
saveExperimentLocally({ ...tempExperiment, id: uuid() })
tempExperiment && saveExperimentLocally({ ...tempExperiment, id: uuid() })
setTempExperiment(undefined)
}

Expand Down
10 changes: 2 additions & 8 deletions components/input-model/categorical-variable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type CategoricalVariableProps = {
export default function CategoricalVariable(props: CategoricalVariableProps) {
const classes = useStyles()
const { isDisabled, onAdded } = props
const [options, setOptions] = useState([])
const [options, setOptions] = useState<string[]>([])
const { register, handleSubmit, reset, formState, setError, clearErrors } =
useForm<CategoricalVariableType>()
const isOptionsValid = useCallback(() => {
Expand Down Expand Up @@ -57,7 +57,6 @@ export default function CategoricalVariable(props: CategoricalVariableProps) {
<>
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
name="name"
{...register('name', { ...validation.required })}
label="Name"
fullWidth
Expand All @@ -67,7 +66,6 @@ export default function CategoricalVariable(props: CategoricalVariableProps) {
helperText={formState.errors.name?.message}
/>
<TextField
name="description"
{...register('description')}
label="Description"
fullWidth
Expand Down Expand Up @@ -97,11 +95,7 @@ export default function CategoricalVariable(props: CategoricalVariableProps) {
setOptions([...options, option])
clearErrors('options')
}}
error={
formState.errors.options !== undefined
? formState.errors.options[0].message
: undefined
}
error={formState.errors.options?.[0].message ?? ''}
/>
<Box mt={2}>
<Button
Expand Down
8 changes: 5 additions & 3 deletions components/layout/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ import Link from 'next/link'
import useStyles from './layout.style'
import { useGlobal } from '../../context/global-context'
import { VersionInfo } from '../version-info'
import { useState } from 'react'
import { FC, useState } from 'react'

export default function Layout({ children }) {
const Layout: FC = ({ children }) => {
const [showDebug, setShowDebug] = useState(false)
const classes = useStyles()
const { state, dispatch } = useGlobal()

const handleSwitch =
flagName => (event: React.ChangeEvent<HTMLInputElement>) => {
(flagName: any) => (event: React.ChangeEvent<HTMLInputElement>) => {
dispatch({ type: flagName, payload: event.target.checked })
}

Expand Down Expand Up @@ -95,3 +95,5 @@ export default function Layout({ children }) {
</>
)
}

export default Layout
2 changes: 1 addition & 1 deletion components/plots/pareto-front-plot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const CustomTooltip = ({ active, payload, label, cheese }: any) => {
</b>
<br />
{payload[0].payload.inputs !== undefined
? payload[0].payload.inputs.map(p => (
? payload[0].payload.inputs.map((p: any) => (
<>
{p.name}: {p.value}
<br />
Expand Down
4 changes: 2 additions & 2 deletions components/result-data/result-data.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const ResultData = (props: ResultDataProps) => {
} = useExperiment()
const global = useGlobal()
const suggestionCount: number = experiment?.extras
? experiment.extras['experimentSuggestionCount']
? (experiment.extras as any)['experimentSuggestionCount']
: 1

return (
Expand Down Expand Up @@ -73,7 +73,7 @@ export const ResultData = (props: ResultDataProps) => {
<NextExperiments suggestionCount={suggestionCount} />
<Suggestions values={nextValues} headers={headers} />
</Box>
{expectedMinimum?.length > 0 && (
{expectedMinimum && expectedMinimum.length > 0 && (
<Box pt={2} pl={2} pr={2} className={classes.extrasContainer}>
<SingleDataPoint
title="Expected minimum"
Expand Down
11 changes: 7 additions & 4 deletions components/upload-csv-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import { DataPointType } from '../types/common'
import { csvToDataPoints } from '../utility/converters'
import PublishIcon from '@material-ui/icons/Publish'

const readFile = (file, dataHandler) => {
const readFile = (
file: File | undefined,
dataHandler: { (data: string): void }
): string => {
var result = ''
if (file) {
const reader = new FileReader()
reader.onload = e => dataHandler(e.target.result as string)
reader.onload = e => dataHandler(e.target?.result as string)
reader.readAsText(file)
}
return result
Expand All @@ -24,8 +27,8 @@ const UploadCSVButton = ({ onUpload, light }: UploadCSVButtonProps) => {
experiment: { valueVariables, categoricalVariables, scoreVariables },
},
} = useExperiment()
const handleFileUpload = e =>
readFile(e.target.files[0], data =>
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) =>
readFile(e?.target?.files?.[0], (data: string) =>
onUpload(
csvToDataPoints(
data,
Expand Down
16 changes: 1 addition & 15 deletions context/experiment-context.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'
import { useExperiment, TestExperimentProvider } from './experiment-context'
import { useExperiment, ExperimentProvider } from './experiment-context'

describe('useExperiment', () => {
it('fails if called outside provider', async () => {
Expand All @@ -13,18 +13,4 @@ describe('useExperiment', () => {
)
expect(console.error).toHaveBeenCalled()
})

it('provides context when called inside provider', async () => {
function ExperimentTester() {
const context = useExperiment()
return <div data-testid="json">{JSON.stringify(context)}</div>
}
render(
<TestExperimentProvider value={{ name: 'test' }}>
<ExperimentTester />
</TestExperimentProvider>
)
const rawJson = screen.getByTestId('json')
expect(rawJson.innerHTML).toEqual(JSON.stringify({ name: 'test' }))
})
})
16 changes: 1 addition & 15 deletions context/experiment-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,6 @@ function ExperimentProvider({
)
}

function TestExperimentProvider({ value, children }) {
return (
<ExperimentContext.Provider value={value}>
{children}
</ExperimentContext.Provider>
)
}

function useExperiment() {
const context = React.useContext(ExperimentContext)
if (context === undefined) {
Expand All @@ -109,10 +101,4 @@ async function runExperiment(dispatch: Dispatch, experiment: ExperimentType) {
dispatch({ type: 'registerResult', payload: result })
}

export {
ExperimentProvider,
TestExperimentProvider,
useExperiment,
saveExperiment,
runExperiment,
}
export { ExperimentProvider, useExperiment, saveExperiment, runExperiment }
2 changes: 1 addition & 1 deletion context/global-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const GlobalContext = React.createContext<
{ state: State; dispatch: Dispatch } | undefined
>(undefined)

function GlobalStateProvider({ children }) {
const GlobalStateProvider: React.FC = ({ children }) => {
const [state, dispatch] = useLocalStorageReducer(
reducer,
initialState,
Expand Down
2 changes: 1 addition & 1 deletion hooks/useLocalStorageReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const useLocalStorageReducer = <S, A>(
reducer: (state: S, action: A) => S,
initialState: S,
localStorageKey: string = 'rootState',
transform = x => x
transform = (x: S) => x
) => {
const localStorageReducer = (state: S, action: A) => {
const newState = reducer(state, action)
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"@types/node": "^16.9.4",
"@types/react": "^17.0.22",
"@types/rimraf": "^3.0.0",
"@types/uuid": "^8.3.4",
"eslint": "7.32.0",
"eslint-config-next": "11.1.2",
"git-revision-webpack-plugin": "^5.0.0",
Expand Down
6 changes: 3 additions & 3 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { AppProps } from 'next/app'
import { useEffect } from 'react'
import { FC, useEffect } from 'react'
import Head from 'next/head'
import CssBaseline from '@material-ui/core/CssBaseline'
import { GlobalStateProvider } from '../context/global-context'

function SafeHydrate({ children }) {
const SafeHydrate: FC = ({ children }) => {
return (
<div suppressHydrationWarning>
{typeof window === 'undefined' ? null : children}
Expand All @@ -17,7 +17,7 @@ function App({ Component, pageProps }: AppProps) {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side')
if (jssStyles) {
jssStyles.parentElement.removeChild(jssStyles)
jssStyles.parentElement?.removeChild(jssStyles)
}
}, [])
return (
Expand Down
9 changes: 9 additions & 0 deletions pages/api/experiment/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ const handler = async (
switch (method) {
case 'GET':
const store =
// @ts-expect-error
db[queryId] || readFromFile(path.join(dbFolder, `${queryId}.json`))
if (store) {
res.json(store)
Expand All @@ -90,23 +91,31 @@ const handler = async (
}
break
case 'PUT':
// @ts-expect-error
db[queryId] = JSON.parse(body)
// @ts-expect-error
writeToFile(path.join(dbFolder, `${queryId}.json`), db[queryId])
// @ts-expect-error
res.json(db[queryId])
break
case 'POST':
const experiment = JSON.parse(body)
const json = await runExperiment(experiment)
const result: ExperimentResultType = {
id: experiment.id,
// @ts-expect-error
plots:
json.plots &&
json.plots.map(p => {
return { id: p.id, plot: p.plot }
}),
// @ts-expect-error
next: json.result.next,
// @ts-expect-error
pickled: json.result.pickled,
// @ts-expect-error
expectedMinimum: json.result.models.find(() => true)?.expectedMinimum,
// @ts-expect-error
extras: json.result.extras,
}
res.json(result)
Expand Down
2 changes: 2 additions & 0 deletions reducers/experiment-reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,5 +191,7 @@ export const experimentReducer = (
})
}
return newState
default:
return experimentState
}
}
2 changes: 1 addition & 1 deletion store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const emptyExperiment: ExperimentType = {
name: '',
description: '',
swVersion: versionInfo.version,
dataFormatVersion: undefined,
dataFormatVersion: '',
},
categoricalVariables: [],
valueVariables: [],
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"useUnknownInCatchVariables": false,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
Expand Down
3 changes: 2 additions & 1 deletion utility/migration/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const bumpVersion = (json: any, version: string): any => {
const convertTo3 = (json: any): any => {
return {
...json,
valueVariables: json.valueVariables.map(v => {
valueVariables: json.valueVariables.map((v: any) => {
return {
name: v.name,
description: v.description,
Expand Down Expand Up @@ -78,6 +78,7 @@ const convertTo5 = (json: ExperimentType): ExperimentType => {
},
],
dataPoints: json.dataPoints.map(dps =>
// @ts-expect-error
dps.map(dp => (dp.name === 'score' ? { ...dp, value: dp.value[0] } : dp))
),
}
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,11 @@
dependencies:
"@types/jest" "*"

"@types/uuid@^8.3.4":
version "8.3.4"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.4.tgz#bd86a43617df0594787d38b735f55c805becf1bc"
integrity sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw==

"@types/yargs-parser@*":
version "21.0.0"
resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.0.tgz#0c60e537fa790f5f9472ed2776c2b71ec117351b"
Expand Down

0 comments on commit 4ce7165

Please sign in to comment.