繁体   English   中英

我可以在 io-ts 中使用 TypeScript 类型吗

[英]Can I use type of TypeScript in io-ts

我正在使用 io-ts 验证 api 响应。 https://github.com/gcanti/io-ts

我已经定义了以下类型的 TypeScript。

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

我想在 io-ts 中使用这种类型,如下所示。

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

但是我遇到了以下错误。

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

有没有办法在 io-ts 代码中使用 Group ?

对您的问题的评论已经提到了这一点,但为了说明如何使用io-ts不要重复自己,您可以说:

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),
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM