gcanti / io-ts-types

A collection of codecs and combinators for use with io-ts
https://gcanti.github.io/io-ts-types/
MIT License
311 stars 40 forks source link

Compile issues when using newtypes & recursive types #178

Closed nhenin closed 1 year ago

nhenin commented 1 year ago

🐛 Bug report

Current Behavior

import * as t from "io-ts";
import { iso, Newtype } from "newtype-ts";
import { fromNewtype } from "io-ts-types";

type  TokenName = Newtype<{ readonly TokenName: unique symbol }, string> ;
const TokenName = fromNewtype<TokenName>(t.string)

type Test = { role_token: TokenName }
const b : t.Type<Test> = t.type({role_token:TokenName})

gives me the following compile issue on b :

Type 'TypeC<{ role_token: Type<TokenName, string, unknown>; }>' is not assignable to type 'Type<Test, Test, unknown>'.
  Types of property 'encode' are incompatible.
    Type 'Encode<{ role_token: TokenName; }, { role_token: string; }>' is not assignable to type 'Encode<Test, Test>'.
      Type '{ role_token: string; }' is not assignable to type 'Test'.
        Types of property 'role_token' are incompatible.
          Type 'string' is not assignable to type 'TokenName'.

I'd like to use these components in a some Recursive Types..

Your environment

Software Version(s)
fp-ts 2.13.1
io-ts 2.2.20
io-ts-types 0.5.19
TypeScript 4.9.5
mlegenhausen commented 1 year ago

The default output parameter O from t.Type is A. So your code evaluates to t.Type<Test, Test> which is not correct as your newtype output will be string and not TokenName. You need to define the output manually.

import * as t from "io-ts";
import { iso, Newtype } from "newtype-ts";
import { fromNewtype } from "io-ts-types";

type  TokenName = Newtype<{ readonly TokenName: unique symbol }, string> ;
const TokenName = fromNewtype<TokenName>(t.string)

type Test = { role_token: TokenName }
type TestOutput = { role_token: string }
const b : t.Type<Test, TestOutput> = t.type({role_token:TokenName})

or just let typescript infer the type.

nhenin commented 1 year ago

Thanks :-)