Skip to content

TypeScript library for making classes from interfaces without repeating the properties

License

Notifications You must be signed in to change notification settings

Qlever-LLC/interface2class

Repository files navigation

@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

About

TypeScript library for making classes from interfaces without repeating the properties

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published