Skip to content

How to annotate enum fields #3

Description

@haraldk

It would be nice if you could add some documentation on how to annotate enum fields.

As an example, I have:

export enum Currency {
  USD,
  EUR
}

class Price {
  private value: number; // It's really a "BigDecimal" type don't worry ;-)
  private currency: Currency;
}

I have tried the following:

No annotation:

class Price {
  // ...
  private currency: Currency;

Result:

No error. No conversion ("currency" is a string, as in the original JSON).

Take two, with @dataType() annotation:

class Price {
  // ...

  @dataType(Currency)
  private currency: Currency;

Result:

Error (I'm no TypeScript expert, but it seems that enums don't have constructors), "Cannot read property 'constructor' of undefined"

TypeError: Cannot read property 'constructor' of undefined
    at Object.getTypeOfCtor (http://localhost:4200/vendor.js:162163:37)
    at deserialize (http://localhost:4200/vendor.js:162083:42)
	...

Take three, with additional @converters():

class Price {
  // ...

  @dataType(Currency)
  @converters({
    'string': (currency: string) => Currency[currency]
  })
  private currency: Currency;

Result:

Exaclty the same error as the previous attempt, "Cannot read property 'constructor' of undefined"

TypeError: Cannot read property 'constructor' of undefined
    at Object.getTypeOfCtor (http://localhost:4200/vendor.js:162163:37)
    at deserialize (http://localhost:4200/vendor.js:162083:42)
	...

In desperation, with only @converters():

class Price {
  // ...

  @converters({
    'string': (currency: string) => Currency[currency]
  })
  private currency: Currency;

Result:

Unsurprisingly this didn't work, but the error message is a little odd. Not sure why it expects a string, when the type is an enum? "Converter output type invalid for property Price.currency, expected string received number."

Error: Converter output type invalid for property Price.currency, expected string received number.
    at deserialize (http://localhost:4200/vendor.js:162107:35)
	...

So... How am I supposed to do it? Or is this a missing feature?

Best regards,

--
Harald K

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions