r/typescript • • Jul 24 '25

type system failure

For this code:

interface Encoder<T> {
  encode(v: T): string,
}

const ID_ENC:  Encoder<string> =  {
  encode: (v) => v,
}

function runEncoder<T>(enc: Encoder<T>, i: T): string {
  return enc.encode(i);
}

function getId(): string | undefined {
  return undefined;
}

function f() {
  const id  = getId();

  ID_ENC.encode(
    id       // GOOD: fails to typecheck
  );

  return runEncoder(
    ID_ENC,
    id       // BAD: should fail to typecheck, but doesn't
  );
}

the typescript compiler (5.3.8) fails to detect type errors that I believe it should. On the line marked GOOD, tsc correctly reports:

TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

21     id       // GOOD: fails to typecheck
       ~~

Should it not also show the same error for the line marked BAD?

4 Upvotes

6 comments sorted by

View all comments

Show parent comment

4

u/timbod Jul 24 '25

> because it intentionally, but unsoundly, treats function parameters as bivariant.

Thank you - this is exactly the explanation I required. It makes me worry about all the other places where type system unsoundness was chosen for pragmatic reasons.

1

u/Rustywolf Jul 24 '25

Another example is probably indexing an array not returning a union with undefined unless you enable noUncheckedIndexedAccess

1

u/prehensilemullet Jul 24 '25 edited Jul 24 '25

Here's the other main one that comes to mind:

const x: {a: number, b: number} = {a: 1, b: 2}
const y: {a: number, b?: number} = x // TS unsoundly allows this assignment

y.b = undefined

const z: number = x.b // no error, yikes

Note, I used Flowtype in the old days and it was a lot more strict and sound about this kind of thing, but it could also be quite a pain to deal with that strictness (you could only assign x to $ReadOnly<{a: number, b?: number}> for example)

I think a more sound but still convenient language would need declarations to be readonly by default and require a mutable keyword or something like that