Node type and view interface inference from schema #805
-
Thank you for this really great library. I also like the coding style. However, I have trouble with node types. What I want to do is to pass a node to a function and that is why I need the type of it. I tried several ways including type inference, but it did not work. Here is an explicit example:
The last line gives the following error:
What am I doing wrong? Or in other words: What ist the correct type of the node? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
This might to be a false positive from eslint. The code seems to works. So I am not sure if this is really a problem of json-joy. |
Beta Was this translation helpful? Give feedback.
-
Basically, what you want to write is: const SimpleObjectSchema = s.obj({
text: s.con<string>('foo'),
});
const model = Model.create(SimpleObjectSchema);
type SimpleObjectNodeType = SchemaToJsonNode<typeof SimpleObjectSchema>;
type SimpleObjectI = JsonNodeView<SimpleObjectNodeType>;
console.log(model + ''); The |
Beta Was this translation helpful? Give feedback.
-
To infer the model view interface there is also an option to do this: type SimpleObjectI = ReturnType<(typeof model)['view']>; |
Beta Was this translation helpful? Give feedback.
-
Another option is: if the type safety results into too much wrestling with the TypeScript compiler, then just don't make it type safe. Cast the model to |
Beta Was this translation helpful? Give feedback.
-
Thank you very much for these helpful hints!
|
Beta Was this translation helpful? Give feedback.
SimpleObjectSchema
, you can extract the node type and view interface from it..api.root()
, the schema does it for you.Basically, what you want to write is:
The
SchemaToJsonNode
andJsonNodeView
types you can import from the library.