logoalt Hacker News

dwatttttyesterday at 5:57 AM3 repliesview on HN

What should a type checker say about this code?

  x = []
  x.append(1)
  x[0] = "new"
  x[0] + "oops"

It's optionally typed, but I would credit both "type checks correctly" and "can't assign 'new' over a number" as valid type checker results.

Replies

jitlyesterday at 7:25 PM

TypeScript widens the type of x to allow `number | string`, there are no type errors below:

    const x = []
    x.push(1)
    type t = typeof x
    //   ^? type t = number[]
    x[0] = "new"
    type t2 = typeof x
    //   ^? type t2 = (number | string)[]
    const y = x[0] + "oops"
    //    ^? const y: string
https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABA...
MangoToupeyesterday at 5:58 AM

It depends on the semantics the language specifies. Whether or not the annotations are optional is irrelevant.

Either way, you didn't annotate the code so it's kind of pointless to discuss.

Also fwiw python is typed regardless of the annotations; types are not optional in any sense. Unless you're using BCPL or forth or something like that

show 1 reply