JohnWeisz / TypedJSON

Typed JSON parsing and serializing for TypeScript that preserves type information.
MIT License
603 stars 64 forks source link

Property default values #149

Closed zoechi closed 3 years ago

zoechi commented 3 years ago

Thanks a lot for this library!

Is there a way to provide default values for properties?

@jsonObject
export class Foo {
  @jsonMember
  bar:string = 'bar';
}

does not work for me. If the value is not provided in the JSON the property is undefined.

MatthiasKunnen commented 3 years ago

This seems to be working fine for me with TypedJSON 1.5.2.

@jsonObject
class Foo {
    @jsonMember
    bar: string = 'bar';
}

TypedJSON.parse({}, Foo); // Foo { bar: 'bar' }
TypedJSON.parse({bar: undefined}, Foo); // Foo { bar: 'bar' }
TypedJSON.parse({bar: null}, Foo); // Foo { bar: 'bar' }
zoechi commented 3 years ago

Thanks for looking into it! I'll check again and reopen if I can provide a simple reproduction.