Creating a TypeScript “non-enumerable” property decorator

Home / TypeScript / Creating a TypeScript “non-enumerable” property decorator


Creating a TypeScript “non-enumerable” property decorator

This post explains how to create a TypeScript property decorator that allows hiding a class property in enumerators.
If you are new to TypeScript or it’s decorators, you might start here first.

Why should I be able to exclude a class property from being enumerated

Well, one good reason is to exclude the property from being included in the JSON representation of the class instance.

For example, let’s look at a simple class:

Now let’s look at the JSON representation of a class instance:

This will print

OK, so we do not want our password to be serialized in our JSON.
Let’s create a decorator to prevent this.

Creating the decorator

Put the following code into a TypeScript file.

Make sure you have the following properties enabled in your tsconfig.json file:

Let the transpiler do it’s work and you should be ready to use your decorator.
Change your User class as follows:

If we re-test the JSON representation of a class instance:

This will print

Job well done!