ts-json-schema-generator icon indicating copy to clipboard operation
ts-json-schema-generator copied to clipboard

Handling of Symbol properties

Open joshkel opened this issue 4 years ago • 2 comments

I have some objects with parent-child relationships, so I'm using Symbols to store the parent relationships. That way, the parent property will be automatically skipped when serializing to JSON.

export const Parent = Symbol('parent');

export interface Entity {
  [Parent]?: Entity;
  children?: Entity[];
  // etc.
}

When I run these types through ts-json-schema-generator, it still tries to create schema definitions for the Parent symbol, using a munged name (__@Parent@21371).

I don't expect symbols to show up in JSON; JSON.stringify completely ignores all Symbol-keyed properties (see here). For now, I've tweaked my schema generation to remove the munged properties. That isn't hard, but it seems to me that ts-json-schema-generator should skip symbols (either always or optionally and by default).

Thoughts? I can submit a PR if this change seems reasonable.

I saw a PR requesting symbol support at #606. This suggestion would seem to go against that - but I'm afraid I don't understand the use of a Record<symbol, string> for serializing to JSON, and current TypeScript rejects the use case in that PR. (See here.) Maybe the skip-symbol behavior I'm describing needs to be an option to accommodate previous code, or maybe it should be restricted to unique symbols.

(I also reported this issue at https://github.com/YousefED/typescript-json-schema/issues/398.)

joshkel avatar Oct 15 '21 15:10 joshkel

Fixed in #989

domoritz avatar Oct 15 '21 16:10 domoritz

Apologies if I didn't explain well - this and #989 are different issues. #989 fixes an issue where ts-json-schema-generator didn't handle typeof Foo at all if Foo was an inferred unique symbol. This question / suggestion is about the handling of symbols (whether explicitly unique, inferred unique, or non-unique) as object keys.

joshkel avatar Oct 15 '21 16:10 joshkel