Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create an optional field type while creating io-ts types #629

Open
sravanmca21 opened this issue Jan 31, 2022 · 1 comment
Open

Comments

@sravanmca21
Copy link

Hi ,

Could you please help me in how to create an optional field while creating io-ts types
for e.g. in below code "contact" type , how to make addressDetails as an optional field like typescript optional field with (?)

import * as t from 'io-ts'

export const address = t.type({
addressline1: t.string,
city: t.string
countryName: t.string
})

export const email = t.type({
emailId: t.string,
})

export const phone= t.type({
number: t.string,
extn: t.string
})

export const contact = t.type {
addressDetails: address, // need to make only addressDetails as an optional field
email: email, // need this as required
phone: phone // need this as required
})

@david-zacharias
Copy link

You can use an intersection

export const contact = t.intersection([
  t.partial({
    addressDetails: address
  }),
  t.type({
    email,
    phone
  })
])

export type contact = t.TypeOf<typeof contact>

See also docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants