You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Say I have the following validation function which takes an object which can have a property that is either a string or a string array, but always returns an object with that property as a string:
importjsonValidatorfrom'is-my-json-valid';functiongetValidBody(body: unknown): {name: string}{constvalidator=jsonValidator({type: 'object',properties: {name: {oneOf: [{type: 'string'},{type: 'array',items: {type: 'string'}}]}},required: ['name']});if(!validator(body)){thrownewError();}if(Array.isArray(body.name)){body.name=JSON.stringify(body.name);// error TS2322: Type 'string' is not assignable to type 'never'.}returnbody;}constbody=getValidBody({name: []});console.log(body);
After the validation is done, body.name has a type of never, but it should be string | string[]. This causes two issues:
As in the example above, if you try to assign anything to body.name it gives an error
If I remove the if (Array.isArray(body.name)) block, the function will happily return an object of type {name: string[]} (although it considers it to be {name: never}), which contradicts the declared return type.
The text was updated successfully, but these errors were encountered:
Say I have the following validation function which takes an object which can have a property that is either a string or a string array, but always returns an object with that property as a string:
After the validation is done,
body.name
has a type ofnever
, but it should bestring | string[]
. This causes two issues:body.name
it gives an errorif (Array.isArray(body.name))
block, the function will happily return an object of type{name: string[]}
(although it considers it to be{name: never}
), which contradicts the declared return type.The text was updated successfully, but these errors were encountered: