Io-ts: Question: best approach for readonly props?

Created on 7 Feb 2020  路  2Comments  路  Source: gcanti/io-ts

Hi, I'am a bit confused how to get readonly props on a type.

What I want

type Foo = {
  readonly bar: string;
  readonly baz: readonly string[];
}

What I expected

import * as t from 'io-ts';

export const Foo = t.type({
  bar: t.readonly(t.string),
  baz: t.readonlyArray(t.string),
});

type Foo = t.TypeOf<typeof Foo>;

// vscode type preview:
type Foo = {
    bar: {
        readonly [x: number]: string;
        readonly toString: () => string;
        readonly charAt: (pos: number) => string;
        readonly charCodeAt: (index: number) => number;
        readonly concat: (...strings: string[]) => string;
        ... 39 more ...;
        readonly trimRight: () => string;
    };
    baz: readonly string[];
}

What actually worked

import * as t from 'io-ts';

export const Foo = t.type({
  bar: t.string,
  baz: t.readonlyArray(t.string),
} as const);

type Foo = t.TypeOf<typeof Foo>;

// vscode type preview:
type Foo = {
    readonly bar: string;
    readonly baz: readonly string[];
}

My question is now: Is this the recommended way or did I miss something? Maybe some more examples in the README.md could help.

Most helpful comment

@bobaaaaa the official way would be:

export const Foo = t.readonly(
  t.type({
    bar: t.string,
    baz: t.readonlyArray(t.string)
  })
)

but this is an interesting side effect of mapped types (which preserve readonlyness):

export const Foo = t.type({
  bar: t.string,
  baz: t.readonlyArray(t.string)
} as const)

All 2 comments

@bobaaaaa the official way would be:

export const Foo = t.readonly(
  t.type({
    bar: t.string,
    baz: t.readonlyArray(t.string)
  })
)

but this is an interesting side effect of mapped types (which preserve readonlyness):

export const Foo = t.type({
  bar: t.string,
  baz: t.readonlyArray(t.string)
} as const)

Ah nice, thanks for the quick answer. I'am still starting to learn the api :)

Pretty awesome lib 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

spacejack picture spacejack  路  3Comments

leemhenson picture leemhenson  路  9Comments

Picoseconds picture Picoseconds  路  3Comments

philipp-schaerer-lambdait picture philipp-schaerer-lambdait  路  3Comments

xogeny picture xogeny  路  5Comments