jsonObject - Property has no initializer
Opened this issue · 1 comments
Hello,
probably I'm missing something simple. I created a class with the @jsonObject
annotation like in the example:
import 'reflect-metadata';
import { jsonObject, jsonMember } from 'typedjson';
@jsonObject
class AClass {
@jsonMember
public prop: string;
}
The problem is at compiling:
error TS2564: Property 'prop' has no initializer and is not definitely assigned in the constructor.
7 public prop: string;
Well, the error makes sense for me but how should it work?
Hey @staxx6, this is actually related to an option in typescript called "strictNullChecks", and is not specific to TypedJSON. There are a couple of ways to deal with it, depending on your use case really.
If you are expecting that this property may not be in an input you could make this property optional with ?
, or provide a default value. Internally, TypedJSON first calls your constructor without any parameters, and then sets all the properties.
On the other hand, if you are sure that this value will always appear in an input, then you could put an assertion on the property with !
. You can then also add required: true
in the decorator options to tell TypedJSON to double check that in the runtime.
Unfortunately at this point, decorators cannot modify a property type, so we have to obey the typescript rules.