Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Created October 31, 2020 16:04
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pmuellr/60668d33049f96ce7323f5eab648f468 to your computer and use it in GitHub Desktop.
Save pmuellr/60668d33049f96ce7323f5eab648f468 to your computer and use it in GitHub Desktop.
trying to use zod in js with jsdoc type comments for vs code - almost works!
'use strict'
// examples from https://github.com/vriad/zod
// trying to use zod in JS w/ jsdoc type comments in vsCode
const z = require('zod')
const dogSchema = z.object({
name: z.string(),
neutered: z.boolean(),
})
/** @typedef { z.infer<typeof dogSchema> } Dog */
/** @type { Dog } */
const cujo = dogSchema.parse({
name: 'Cujo',
neutered: true,
})
console.log(cujo)
/** @type { Dog } */
const cujo2 = {
name: 'Cujo2',
neutered: false
}
console.log(cujo2)
try {
/** @type { Dog } */
dogSchema.parse({
name: 'Fido',
})
} catch (err) {
console.log(err.message)
}
// the following should be an type error, but Dog is defined in vsCode
// as a "partial", but shouldn't be
/** @type { Dog } */
const fido2 = {
name: 'Fido2'
}
console.log(fido2)
@anthonyjonahs
Copy link

Extremely late to the party here, but updating the jsconfig.json for my project as follows worked for me:

// jsconfig.json
{
  // ...
  "compilerOptions": {
    // ...
    "strict": true
  }
}    

Zod docs say to do this when getting started, but for TS project: https://zod.dev/?id=requirements

@pmuellr
Copy link
Author

pmuellr commented Jun 8, 2023

Interesting - I haven't been using that lately with my jsdoc-fueled projects, this may explain some other weirdness I've seen ...

@pmuellr
Copy link
Author

pmuellr commented Jun 8, 2023

First downside is that I have to add extra stuff to deal with try/catch errors; the error from catch() is now unknown, previously any. But it caught more valid issues, so ... seems like a weiner!

Thanks a bunch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment