logoalt Hacker News

sargunvtoday at 8:55 AM4 repliesview on HN

Even with strict flags on, there are failures. A trivial example:

  function mutateArray(
    arr: (string | number)[]
  ) {
    arr.push(1);
  }
  const a: string[] = ["one", "two"];
  mutateArray(a);
a is now a string[] with a number inside

Replies

stratos123today at 3:27 PM

Woah, that's quite an issue. The equivalent code in Python doesn't typecheck, since `list` is invariant and hence list[str] doesn't fit list[str|int]. Unusual for TS to handle types worse than Python.

drzaiusx11today at 1:43 PM

Yikes. I've only been using ts for about a year, I had no idea this was considered a "valid" case. Seems like a type error to me. I wonder how they justify this?

teaearlgraycoldtoday at 9:06 AM

Very interesting. I’m shocked the typescript creators built a system with this failure mode. I guess the solution here is to have tsc change the type of “a” after the call to mutateArray, unless the arr argument is marked as readonly.

Is there a name for this failure mode?

show 4 replies