Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jsonObject - Property has no initializer #124

Open
staxx6 opened this issue Feb 13, 2020 · 1 comment
Open

jsonObject - Property has no initializer #124

staxx6 opened this issue Feb 13, 2020 · 1 comment

Comments

@staxx6
Copy link

staxx6 commented Feb 13, 2020

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?

@Neos3452
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants