This module provides a bunch of functions to create and implement traits.
A trait is the special kind of abstract class that is used as an interface.
Why would we need that? Well, unlike Java or Kotlin, TypeScript interfaces can't have default implementations of methods.
So we need to implement each method in our classes even if the implementation doesn't change.
This is where traits come into play. How it works? Ok, let's enumerate the steps to create a trait:
Create an abstract class, where define all necessary abstract methods and properties (yes, the trait can also define properties,
not only methods).
Define the non-abstract methods as static class methods with the same names and signatures but add as the first parameter
a link to the class instance, as we do it in Python or Rust. Also, we can use the AddSelf helper to produce less code.
// The first parameter provides a method to wrap. // The second parameter declares which type has `self`. staticgetQuack: AddSelf<Duckable['getQuack'], Duckable> = (self, size) => { if (size < 10) { return'quack!'; }
if (size < 20) { return'quack!!!'; }
return'QUACK!!!'; }; }
We have created a trait. Now we can implement it in a simple class.
Create a simple class and implement the trait by using the implements keyword.
Don't implement methods, which you want to store their default implementations.
Derives the provided traits to a class.
The function is used to organize multiple implementing interfaces with the support of default methods.
decorator
example
abstractclassInterface1 { abstractbar(): string;
/** * The method that have the default implementation. * The implementation is placed as a static method. *\/ bla(a: number): number { return Object.throw(); };
/** * The default implementation for `Interface1.bla`. * As the first parameter, the method is taken a context. * * @seeInterface1.bla *\/ static bla: AddSelf<iFoo['bla'], Baz> = (self, a) => a + 1; }
abstract class Interface2 { abstract bar2(): string;
core/functools/trait
This module provides a bunch of functions to create and implement traits. A trait is the special kind of abstract class that is used as an interface. Why would we need that? Well, unlike Java or Kotlin, TypeScript interfaces can't have default implementations of methods. So we need to implement each method in our classes even if the implementation doesn't change. This is where traits come into play. How it works? Ok, let's enumerate the steps to create a trait:
return Object.throw()
.AddSelf
helper to produce less code.We have created a trait. Now we can implement it in a simple class.
implements
keyword. Don't implement methods, which you want to store their default implementations.Trait
type.derive
decorator fromcore/functools/trait
with our class and provide all traits that we want to implement automatically.Besides, regular methods, you can also define get/set accessors like this: