ts-json-schema-generator
ts-json-schema-generator copied to clipboard
Object.freeze of a "as const" causes a Cannot read property 'map' of undefined
Work as expected
When defining a typescript type from an array const, ts-json-schema-generator works as expected, and output the correct json schema.
shared/src/foo.ts
export const MEDIA_TYPES = ['image', 'video'] as const;
type MediaType = typeof MEDIA_TYPES[number];
export class Media {
type?: MediaType
}
./node_modules/.bin/ts-json-schema-generator --path shared/src/foo.ts
Generate the correct json schema.
Issue when using Object.freeze
However, if we try to freeze the array, Typescript works as expected, meaning the type gets inferred as the previous case, but ts-json-schema-generator, output a Cannot read property 'map' of undefined error
shared/src/foo.ts
export const MEDIA_TYPES = Object.freeze(['image', 'video'] as const);
type MediaType = typeof MEDIA_TYPES[number];
export class Media {
type?: MediaType
}
./node_modules/.bin/ts-json-schema-generator --path shared/src/foo.ts
/....project..../node_modules/ts-json-schema-generator/dist/ts-json-schema-generator.js:45
throw error;
^
TypeError: Cannot read property 'map' of undefined
at CallExpressionParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/NodeParser/CallExpressionParser.js:19:67)
at ChainNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/ChainNodeParser.js:28:54)
at TypeofNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/NodeParser/TypeofNodeParser.js:31:45)
at ChainNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/ChainNodeParser.js:28:54)
at IndexedAccessTypeNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/NodeParser/IndexedAccessTypeNodeParser.js:21:71)
at ChainNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/ChainNodeParser.js:28:54)
at TypeAliasNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/NodeParser/TypeAliasNodeParser.js:33:43)
at AnnotatedNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/NodeParser/AnnotatedNodeParser.js:19:47)
at ExposeNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/ExposeNodeParser.js:17:45)
at CircularReferenceNodeParser.createType (/....project..../node_modules/ts-json-schema-generator/dist/src/CircularReferenceNodeParser.js:21:43)
Notes
In our code base, we need to export the possible values of those types for other reasons than just validation, but also need to make sure they are frozen to avoid accidental tampering. Typescript supports this transparently, and we were planning to use ts-json-schema-generator, but now we would need to add extra code to export the frozen array, and have the unfrozen one for internal typing.