ts-copyable
v0.1.0
Published
Type-safe .copy() for TypeScript inspired by Scala case-class
Downloads
5
Readme
ts-copyable
Type-safe .copy() for TypeScript inspired by Scala case-class
How to install
$ npm install --save ts-copyable
How to use
Before
class Person{
constructor(readonly name: string, readonly age: number){
}
}
After
import { Copyable } from 'ts-copyable';
class Person extends Copyable<Person>{
constructor(readonly name: string, readonly age: number){
super(Person);
}
}
Then your Person
class is copyable!
const p1 = new Person("jack", 10);
p1.copy({age: 2});
// => Person("jack", 2)
p1.mapCopy({age: prev => prev+1});
// => Person("jack", 11)
How about type-safety?
const p1 = new Person("jack", 10);
p1.copy({age: "abc"});
// Compile error (GOOD!)
p1.copy({somethingElse: 99});
// Compile error (GOOD!)
p1.mapCopy({age: prev => prev+"abc"});
// Compile error (GOOD!)