Skip to content
This repository was archived by the owner on Jun 29, 2021. It is now read-only.

Document the use of ! for required props #232

Closed
ctrlplusb opened this issue Dec 26, 2018 · 4 comments · Fixed by #350
Closed

Document the use of ! for required props #232

ctrlplusb opened this issue Dec 26, 2018 · 4 comments · Fixed by #350

Comments

@ctrlplusb
Copy link

ctrlplusb commented Dec 26, 2018

It appears that when strictPropertyInitialization is enabled you need to add a ! to the definitions of any of your props that are "required" otherwise you will see a TS error similar to "Property 'foo' has no initialiser and is not definitely assigned in the constructor".

e.g.

export class User extends Typegoose {
  @prop({ required: true })
  name!: string;

  @prop({ required: false })
  name?: age;
}

Related:

@WangLarry
Copy link

Try adding "strictPropertyInitialization": false to your compiler options.

@dgreene1
Copy link

dgreene1 commented Feb 8, 2019

@WangLarry in general, would not recommend turning off "strictPropertyInitialization". It's there to prevent a class from having a constructor that forgets to set each of the properties. But I suppose in Mongo/Mongoose, it might be easier to not have a constructor due to number of methods that exist on each class. So I suppose "strictPropertyInitialization" is not a good match for a Mongo/Mongoose project.

@ctrlplusb but academically speaking, I think the correct way to correct the TS error is:

export class User extends Typegoose {
  @prop({ required: true })
  name: string;

  constructor(name:string){
    this.name = name;
  }
}

After you do that, then your class will always have a way of ensuring that name is set. As for the use of !, that's just a way of telling TypeScript that "no it really is a truthy string." But in practice, you have no way of preventing someone from doing the following:

const aNamelessUser = new User();
// But if you add non-default constructor as I showed above, then TypeScript will require you to pass in a name
const aNamedUser = new User("George Smith");

@AlexAtHome
Copy link

AlexAtHome commented Feb 9, 2019

I faced the same problem. I downgraded Typescript from 3.3.3 to 2.9.2 and the error is gone. But, I think, this is not how you want to solve this.

@Drageaux
Copy link

Drageaux commented May 31, 2019

@dgreene1 Wouldn't having a constructor require you to pass in the args in the exact same order when creating a new object? That would generate redundant code (setting props to args) and would disable passing in object literal params new User({age: 33', gender: 'Male', name)).

Imagine if name was your last argument while the rest were nullable, you would have to do this new User(null, null, null, name);

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

Successfully merging a pull request may close this issue.

5 participants