typescripttypesio-ts-library

Can I use a TypeScript type with io-ts?


I am working on validating API responses using io-ts.

I have already defined the following type in regular TypeScript:

export type Group = {
   id: number;
   name: string;
} 

And I want to use this type in io-ts like this:

const UploadedSearch = t.type({
    id: t.number,
    title: t.string,
    groups: t.array(Group),
});

But I get the following error.

TS2693: 'Group' only refers to a type, but is being used as a value here.

Is there any way to use Group in the io-ts code?


Solution

  • The comment on your question already mentioned this but to illustrate how to use io-ts not to repeat yourself, you can say:

    const GroupCodec = t.type({
      id: t.number,
      name: t.string,
    });
    // Will be equivalent to your group type, so no need to repeat yourself.
    export type Group = t.TypeOf<typeof GroupCodec>;
    
    const UploadedSearch = t.type({
      id: t.number,
      title: t.string,
      groups: t.array(GroupCodec),
    });