0

I am wondering how to prevent this from happening?

@jsonReflect()
class TestClass {
    name?: string;
    age?: number;
    @jsonIgnore()
    address?: string;
}
const test = { name : "John", age: 10 };

The problem is, creation of object { name : "John", age: 10 } strips object of class decorators, constructor logic etc. How can I explicitly prevent this behaviour?

There is another deserialization problem when it comes to objects like these { name : "John", age: 10 }. Sometimes, I have classes like this:

export class ConnectorSignature {
    name!: string;
    dataType!: string;
    @jsonIgnore()
    dataReference!: number;
}

Classes like these have to be deserialized through JSON.parse("some string") but after deserialization they also come out as 'objects from scratch'. So, any decorators are gone, any constructor logic is gone and meta is gone really. E.g.

// this will look like ConnectorSignature class, but...
const connectorData: ConnectorSignature = JSON.parse("some string");

// serializing it back will ignore decorator
console.log(JSON.stringify(connectorData));
/* and produce all fields: 
'{
  "name": "Blue",
  "dataType": "Integer",
  "dataReference": 2,
}'
*/

1 Answers1

1

Add any private member to your class:

class TestClass {
    private isClass = true
    name?: string;
    age?: number;
    address?: string;
}

const test1: TestClass = { name : "John", age: 10 }; // error
const test2: TestClass = { name : "John", age: 10, isClass: true }; // error
const test3: TestClass = new TestClass() // fine

Now it's not possible for a simple object to conform to that interface at all.

See Playground

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337