TypeScript abstract class enabling instance initialization from a plain object
npm install ts-class-initializableA small helper for TypeScript classes to enable instance properties to be initialized by passing
a plain object to the constructor - without every class needing boilerplate code to handle this.
Extend one of the Initializable classes and your class constructor will accept a
plain object literal as its first argument, and assign the values to instance properties.
``shell`
npm i ts-class-initializable
`ts
import { Initializable } from 'ts-class-initializable';
class Foo extends Initializable
public bar: string;
public baz: number;
public optional?: boolean;
}
const instance: Foo = new Foo({
bar: 'foobar',
baz: 2,
});
console.log(instance.bar); // 'foobar'
`
There are a few flavours:
- Initializable: the constructor requires a plain object to initialize the instancePartiallyInitializable
- : the constructor requires a plain object to initialize the instance,OptionallyInitializable
but all properties are treated as optional
- : the constructor may accept a plain object to initialize the instance,new Foo()
or you can do without initializationOptionallyPartiallyInitializable`: the constructor may accept a plain object to initialize the instance,
-
and all properties are treated as optional