Why understanding TypeScript matters when using AI

You ask AI for an Order type from your API response. It gives you:

type Order = {
  id: string
  amount: number
  status: string
  discount?: number
}

It compiles. Everything looks good.

The real system only sends four values: 'pending' | 'paid' | 'cancelled' | 'refunded'.

Six weeks in, someone writes if (order.status === 'canceled') with one L.

The code compiles, but the comparison never matches. As a result, the system no longer refunds cancelled orders. You only find out because a customer tells you about the problem, not because the compiler caught it.

Also, is the amount in cents or in rupees?

The type signature does not specify. Nothing stops you from adding a value in cents to a value in rupees. A branded type would make this mistake a compile error: type Cents = number & { readonly brand: unique symbol }.

Then there’s discount?: number.

The question mark means that the key can be absent. But your D1 query returns discount: null, so the key is always present. Thus order.discount ?? 0 gives the correct result by accident, and discount in order is always true.

The correct type here would be discount: number | null.

Subtle. Also critical.

The problem is only compounded because now the wrong type exists in the project. You ask AI for a handler, some tests, and some mock fixtures for your tests. It gives them to you, but it generates everything based on this one shaky type.

// The handler
if (order.status === 'canceled') {
  await refund(order)
}

// The fixture, written from the same type
const order: Order = { id: 'o_1', amount: 5000, status: 'canceled' }

// The test
expect(refund).toHaveBeenCalledWith(order)   // passes

The test passes.

Everything is internally consistent.

We have proved that refunds work.

But the real system never sends the cancelled value with one L, so the code is externally inconsistent.

This is the worst failure mode to debug because your tests are green the whole time. You have cemented over the problem.

Asking AI to “make type errors go away” won’t work here.

This is why understanding TypeScript matters when you use AI to generate code.

 
0
Kudos
 
0
Kudos

Now read this

typescript

Variables # let apples = 5; let speed: string = 'fast'; let hasName: boolean = true; let nothingMuch: null = null; let nothing: undefined = undefined; Built in objects # let now: Date = new Date(); Arrays # let colors: string[] = ['red',... Continue →