Demo, all content is generated
Question

ChatGPT fixed my TypeScript errors by putting 'as any' everywhere, how do I undo that properly

Solved · 611 views · asked by rhys_m · edited

Some months ago I pasted every TS error into ChatGPT and applied the fixes. The build passes, but I just counted 212 as any and : any in my code. Now I get runtime errors like cannot read properties of undefined (reading 'map') that TypeScript should have caught.

Where do I even start without spending 3 weeks?

What I’ve tried

Removed some at random, got 40 errors, put them back.

Comment
Do you have ESLint set up at all? aiko_n · edited

3 answers

Marked as helpful by the asker
katja_s · edited

Don't remove them at random. Remove them where data enters your app, because that's where the runtime errors come from.

  1. Make them visible but not blocking:
    // eslint
    "@typescript-eslint/no-explicit-any": "warn"
  2. Start with API responses and form data. Give them a real type, ideally parsed:
    const Order = z.object({ id: z.string(), items: z.array(Item) });
    const order = Order.parse(await res.json()); // throws early with a clear message
    Your .map of undefined errors will surface as a parse error at the boundary instead of deep in a component.
  3. Where you really don't know the type yet, use unknown, not any. TypeScript forces you to check before use.
  4. Fix everything downstream as the errors appear, one file per commit.

212 sounds like a lot, but most come from a handful of untyped functions. Fixing those 10 usually makes half the rest pointless.

Comment
Typed the 4 fetch helpers with zod, ~90 of the anys became unnecessary and one of them was the .map bug. Chipping away at the rest. rhys_m · edited
mei_lin · edited

Don't forget the invisible anys: JSON.parse() and await res.json() return any without anyone writing as any. Search for those first, that's usually where the .map-of-undefined bugs are born.

Comment
aiko_n · edited

Tip for the ones in React props: hover the component where it's used and copy the inferred type. Half of them are React.ReactNode or a simple union someone was too lazy to write.

Comment