A TypeScript utility to create a class from an interface without having to duplicate the interface's properties.
yarn add @qlever-llc/interface2class
# type-fest is needed as a devDependency
yarn add -D type-fest
import { makeClass } from '@qlever-llc/interface2class';
interface Foo {
bar: string;
baz: number;
}
class FooClass extends makeClass<Foo>() {
// Add whatever else you want to the class
}
const foo = new FooClass({ bar: 'bar', baz: 1 });
console.log(foo.bar); // 'bar'
console.log(foo.baz); // 1
import { makeClass } from '@qlever-llc/interface2class';
interface Foo {
bar: string;
baz?: number;
}
class FooClass extends makeClass<Foo, 'baz'>() {
constructor({ baz = 4, ...rest }: Foo) {
super({ baz, ...rest }});
// Do whatever else you want in the constructor
}
}
// Property baz is now always defined on foo (and any instance of `FooClass`)
const foo = new FooClass({ bar: 'bar' });
console.log(foo.bar); // 'bar'
console.log(foo.baz); // 4