簡體   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