@qlever-llc/interface2class
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

@qlever-llc/interface2class

Version Coverage Status code style: prettier License

A TypeScript utility to create a class from an interface without having to duplicate the interface's properties.

Installation

yarn add @qlever-llc/interface2class
# type-fest is needed as a devDependency
yarn add -D type-fest

Usage

Basic

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

Adding Defaults

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

Package Sidebar

Install

npm i @qlever-llc/interface2class

Weekly Downloads

3

Version

1.1.0

License

Apache-2.0

Unpacked Size

17.8 kB

Total Files

5

Last publish

Collaborators

  • awlayton