gcanti / io-ts

Runtime type system for IO decoding/encoding
https://gcanti.github.io/io-ts/
MIT License
6.68k stars 331 forks source link

Inference error for `toString` property in intersection types with TypeScript 4.9.5 #696

Closed bogdanb closed 1 year ago

bogdanb commented 1 year ago

šŸ› Bug report

Current Behavior

The following code fails typechecking:

import * as t from "io-ts";

interface Test {
  toString: null | string;
  prop?: unknown;
}

// This works:
const Test1: t.Type<Test> = t.type({
  toString: t.union([t.null, t.string]),
});

// This does not work:
const Test2: t.Type<Test> = t.intersection([
  t.type({
    toString: t.union([t.null, t.string]),
  }, "Req"),
  t.partial({
    prop: t.unknown,
  }, "Opt"),
], "Test2");

The error is:

Type 'IntersectionC<[TypeC<{ toString: UnionC<[NullC, StringC]>; }>, PartialC<{ prop: UnknownC; }>]>' is not assignable to type 'Type<Test, Test, unknown>'.
  Types of property 'encode' are incompatible.
    Type 'Encode<{ toString: string | null; } & { prop?: unknown; }, { toString: string | null; } & { prop?: unknown; }>' is not assignable to type 'Encode<Test, Test>'.
      Type 'Test' is not assignable to type '{ toString: string | null; } & { prop?: unknown; }'.
        Types of property 'toString' are incompatible.
          Type 'string | null' is not assignable to type 'string & (() => string)'.
            Type 'null' is not assignable to type 'string & (() => string)'.
              Type 'null' is not assignable to type 'string'.

Expected behavior

I would expect the code to just work.

Reproducible example

Please see this playground.

Suggested solution(s)

Iā€™m not actually sure if itā€™s a bug in TS or in io-ts, see below. I could figure out how to make a short example using io-ts but not without it. Hopefully someone who understands the io-ts type hierarchies better than I do can help.

Additional context

The code used to work up to TypeScript 4.8.4, and it no longer works in 4.9.5 (nor in 5.0.4). I canā€™t tell if TypeScript introduced a bug, or if some io-ts type extends something it shouldnā€™t and some change in the type declarations or in the inference rules exposed this.

Note that this specifically happens only if the property is named toString, so presumably it is caused by some interference with Object.toString.

Your environment

I canā€™t figure out how www.typescriptlang.org picks versions, but locally I get the buggy behavior with the versions below:

Software Version(s)
io-ts 2.2.20 & 2.2.16
fp-ts 2.10.5
TypeScript 4.9.5
bogdanb commented 1 year ago

I managed to reproduce this with out io-ts, it seems to be a bug in TypeScript.