Hacker News new | ask | show | jobs
by andrewp123 807 days ago
I’ve been working with TypeScript and it’s literally wrong half the time. This code is 100% correct according to TS:

x: number[] = []

y: number = x[0]

The array type is missing information about the length of the array, and types are very often missing important information like this. Say you want to describe an array containing only odd integers - good luck.

Types are simply a heuristic for humans to try and remember vaguely what their code should do. If you want to do anything complex you need to abandon them anyway and use things like x!, and x as my_type. So designing around types seems like a bad idea.

You could do much better by abandoning text based programming languages and creating a visual programming language where you can zoom out and see what information gets passed where. The whole reason for types is to be a hack fix to the problem that we’re too zoomed in on their code and can only really reason about one function at a time given our crappy text-based programming languages.

1 comments

You need

  "noUncheckedIndexedAccess": true
in your tsconfig.json. For odd only numbers, you can make a "branded" type. There are many options, one way is

  type OddNumber = number & { __BRAND_ODD_NUMBER: true }
then it's just

  OddNumber[]
and to onboard untrusted data, use a type guard

  const isOddNumber = (x: unknown): x is OddNumber => typeof x === 'number' && x % 2 === 1