TypeScript dynamic class - combine/remove - javascript

I'm trying to make a dynamic class that is constructed using the components of many other possible classes.
I'm trying to add and remove them using ES6 Object.assign() and can get the variables to copy over but can't seem to get the methods to copy.
Here is an example of what I'm trying to do:
class foo {
salad: string = 'salad';
chop(){
console.log('Chop');
}
}
class man {
nuts: string = 'nuts';
kick(){
console.log('Kick')
}
}
class choo {
add(){
var f: foo = new foo();
var m: man = new man();
//Copy variables
Object.assign(this, f, m);
//Copy methods
//Object.assign(this.prototype, f, m);
}
remove(){
d = Object.getPrototypeOf(foo);
for (key in d){
delete this[key]
}
}
}
var karate = new choo();
karate.add();
//karate.chop();
console.log(karate.salad);
//karate.kick();
console.log(karate.nuts);
I tried to get an example to share on http://fiddlesalad.com/typescript/ but it wouldn't save. The code that is not working is commented out.
Object.assign(this.prototype, obj1) is what is recommended by ES6 to copy prototype functions from one class to another but TypeScript doesn't seem to like it.
Any ideas?

This is a total hack but it seems to do what you're looking for:
function extend < A, B > (d: A,
b: B) {
for (var x in b) d[x] = b[x];
return <A & B > d;
}
interface Object {
assign < P, Q > (a: P,
...b: Q[]): P & Q;
}
interface ifoo {
salad: string;
chop();
}
interface iman {
nuts: string;
kick();
}
class foo implements ifoo {
salad: string = 'salad';
chop() {
console.log('Chop');
}
}
class man implements iman {
nuts: string = 'nuts';
kick() {
console.log('Kick')
}
}
class choo {
foo: foo;
man: man;
add() {
return extend(this, extend(this.foo = new foo(), this.man = new man()));
}
remove() {
Object.keys(this.man).forEach(k => delete this[k]);
return <ifoo><any>this;
}
}
let both = new choo();
var karate = both.add();
console.log("karate", karate);
karate.chop();
console.log(karate.salad);
karate.kick();
console.log(karate.nuts);
let chooman = both.remove();
console.log("karate", karate);
chooman.chop();

First off I'll point out that mixins are probably the correct answer to what I was looking to do.
Here is a good article about mixins:
https://www.stevefenton.co.uk/2014/02/TypeScript-Mixins-Part-One/
That being said, I did figure out a solution that uses Object.assign() although it's probably a bit frowned upon due to mutating __proto__ directly.
Choo will now look like this:
class choo {
add(){
var f: foo = new foo();
var m: man = new man();
//Copy variables
Object.assign(this, f, m);
//Copy methods
Object.assign(this.__proto__, foo.prototype, man.prototype);
}
}
remove() method was deleted because Object.assign() will overwrite class methods if they share the same name. Before testing I wasn't sure if there would be issues with that.

Related

Is it possible to instantiate a class without a `new` operator? [duplicate]

Given a simple class
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
Is it possible to call the class constructor without the new keyword?
Usage should allow
(new Foo("world")).hello(); // "hello world"
Or
Foo("world").hello(); // "hello world"
But the latter fails with
Cannot call a class as a function
Classes have a "class body" that is a constructor.
If you use an internal constructor() function, that function would be the same class body as well, and would be what is called when the class is called, hence a class is always a constructor.
Constructors require the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it's required for the class constructor to create a new instance.
The error message is also quite specific, and correct
TypeError: Class constructors cannot be invoked without 'new'
You could:
either use a regular function instead of a class1.
Always call the class with new.
Call the class inside a wrapping regular function, always using new, that way you get the benefits of classes, but the wrapping function can still be called with and without the new operator2.
1)
function Foo(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
this.hello = function() {
return this.x;
}
}
2)
class Foo {
constructor(x) {
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
var _old = Foo;
Foo = function(...args) { return new _old(...args) };
As others have pointed out, ES2015 spec strictly states that such call should throw TypeError, but at the same time, it provides feature that can be used to achieve exactly the desired result, namely Proxies.
Proxies allows us to virtualize over a concept of an object. For instance, they can be used to change some behaviour of particular object without affecting anything else.
In your specific use case, class Foo is Function object which can be called -- this normally means that body of this function will be executed. But this can be changed with Proxy:
const _Foo = new Proxy(Foo, {
// target = Foo
apply (target, thisArg, argumentsList) {
return new target(...argumentsList);
}
});
_Foo("world").hello();
const f = _Foo("world");
f instanceof Foo; // true
f instanceof _Foo; // true
(Note that _Foo is now the class you want to expose, so identifiers should probably be the other way round)
If run by browsers that support Proxies, calling _Foo(...) will now execute apply trap function instead of the original constructor.
At the same time, this "new" _Foo class is indistinguishable from original Foo (apart from being able to call it as a normal function). Similarly, there is no difference by which you can tell object created with Foo and _Foo.
The biggest downside of this is that it cannot be transpiled or polyfilled, but still it's viable solution for having Scala-like class applied in JS in the future.
Here's a pattern I've come across that really helps me. It doesn't use a class, but it doesn't require the use of new either. Win/Win.
const Foo = x => ({
x,
hello: () => `hello ${x}`,
increment: () => Foo(x + 1),
add: ({x: y}) => Foo(x + y)
})
console.log(Foo(1).x) // 1
console.log(Foo(1).hello()) // hello 1
console.log(Foo(1).increment().hello()) // hello 2
console.log(Foo(1).add(Foo(2)).hello()) // hello 3
i just made this npm module for you ;)
https://www.npmjs.com/package/classy-decorator
import classy from "classy-decorator";
#classy()
class IamClassy {
constructor() {
console.log("IamClassy Instance!");
}
}
console.log(new IamClassy() instanceof IamClassy()); // true
console.log(IamClassy() instanceof IamClassy()); // true
No, this is not possible. Constructors that are created using the class keyword can only be constructed with new, if they are [[call]]ed without they always throw a TypeError1 (and there's not even a way to detect this from the outside).
1: I'm not sure whether transpilers get this right
You can use a normal function as a workaround, though:
class Foo {
constructor(x) {
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
{
const _Foo = Foo;
Foo = function(...args) {
return new _Foo(...args);
};
Foo.prototype = _Foo.prototype;
}
Disclaimer: instanceof and extending Foo.prototype work as normal, Foo.length does not, .constructor and static methods do not but can be fixed by adding Foo.prototype.constructor = Foo; and Object.setPrototypeOf(Foo, _Foo) if required.
For subclassing Foo (not _Foo) with class Bar extends Foo …, you should use return Reflect.construct(_Foo, args, new.target) instead of the new _Foo call. Subclassing in ES5 style (with Foo.call(this, …)) is not possible.
class MyClass {
constructor(param) {
// ...
}
static create(param) {
return new MyClass(param);
}
doSomething() {
// ...
}
}
MyClass.create('Hello World').doSomething();
Is that what you want?
If you need some logic when creating a new instance of MyClass, it could be helpful to implement a "CreationStrategy", to outsorce the logic (for example complex builder logic with validation)
Edit: As discussed in the comments It does not make sense to create some sort of Builder Pattern with a separate class in JavaScript. Removed related example.
Here's a where you can use a 'scope safe constructor'
Observe this code:
function Student(name) {
if(this instanceof Student) {
this.name = name;
} else {
return new Student(name);
}
}
Now you can create a Student object without using new as follows:
var stud1 = Student('Kia');
Dug up this one in the draft
Constructors defined using class definition syntax throw when called as functions
So I guess that's not possible with classes.
Call class constructor manually can be usefull when refactoring code (having parts of the code in ES6, other parts beeing function & prototype definition)
I ended up with a small, yet usefull boilerplate, slicing the constructor into another function. Period.
class Foo {
constructor() {
//as i will not be able to call the constructor, just move everything to initialize
this.initialize.apply(this, arguments)
}
initialize() {
this.stuff = {};
//whatever you want
}
}
function Bar () {
Foo.prototype.initialize.call(this);
}
Bar.prototype.stuff = function() {}
I had problems extending classes converted with the transformation function mentioned in some other answers. The issue seems to be that node (as of v9.4.0) doesn't properly support the argument spread operator ((...args) =>).
This function based on the transpiled output of the classy-decorator (mentioned in another answer) works for me and doesn't require support for decorators or the argument spread operator.
// function that calls `new` for you on class constructors, simply call
// YourClass = bindNew(YourClass)
function bindNew(Class) {
function _Class() {
for (
var len = arguments.length, rest = Array(len), key = 0;
key < len;
key++
) {
rest[key] = arguments[key];
}
return new (Function.prototype.bind.apply(Class, [null].concat(rest)))();
}
_Class.prototype = Class.prototype;
return _Class;
}
Usage:
class X {}
X = bindNew(X);
// or
const Y = bindNew(class Y {});
const x = new X();
const x2 = X(); // woohoo
x instanceof X; // true
x2 instanceof X; // true
class Z extends X {} // works too
As a bonus, TypeScript (with "es5" output) seems to be fine with the old instanceof trick (well, it won't typecheck if used without new but it works anyhow):
class X {
constructor() {
if (!(this instanceof X)) {
return new X();
}
}
}
because it compiles it down to:
var X = /** #class */ (function () {
function X() {
if (!(this instanceof X)) {
return new X();
}
}
return X;
}());
Alright I have another answer here, and I think this one is pretty innovative.
Basically, the problem with doing something similar to Naomik's answer is that you create functions each and every time you chain methods together.
EDIT: This solution shares the same problem, however, this answer is being left up for educational purposes.
So here I'm offering a way to merely bind new values to your methods--which are basically just independent functions. This offer the additional benefit of being able to import functions from different modules into the newly constructed object.
Okay, so here it goes.
const assoc = (prop, value, obj) =>
Object.assign({},obj,{[prop]: value})
const reducer = ( $values, accumulate, [key,val] ) => assoc( key, val.bind( undefined,...$values ), accumulate )
const bindValuesToMethods = ( $methods, ...$values ) =>
Object.entries( $methods ).reduce( reducer.bind( undefined, ...$values), {} )
const prepareInstance = (instanceMethods, staticMethods = ({}) ) => Object.assign(
bindValuesToMethods.bind( undefined, instanceMethods ),
staticMethods
)
// Let's make our class-like function
const RightInstanceMethods = ({
chain: (x,f) => f(x),
map: (x,f) => Right(f(x)),
fold: (x,l,r) => r(x),
inspect: (x) => `Right(${x})`
})
const RightStaticMethods = ({
of: x => Right(x)
})
const Right = prepareInstance(RightInstanceMethods,RightStaticMethods)
Now you can do
Right(4)
.map(x=>x+1)
.map(x=>x*2)
.inspect()
You can also do
Right.of(4)
.map(x=>x+1)
.map(x=>x*2)
.inspect()
You also have the added benefit of being able to export from modules as such
export const Right = prepareInstance(RightInstanceMethods,RightStaticMethods)
While you don't get ClassInstance.constructor you do have FunctorInstance.name (note, you may need to polyfill Function.name and/or not use an arrow function for export for browser compatibility with Function.name purposes)
export function Right(...args){
return prepareInstance(RightInstanceMethods,RightStaticMethods)(...args)
}
PS - New name suggestions for prepareInstance welcomed, see Gist.
https://gist.github.com/babakness/56da19ba85e0eaa43ae5577bc0064456
As pointed out by you and others
Foo("world").hello();
fails with an error because it is an error,
according to rules of ES6 syntax.
Others pointed out that
(new Foo("world")).hello();
works but is clunky because
It needs the 'new' AND
It needs the extra parenthesis.
I agree it is clunky. So I'm often using
this solution instead:
In your class Foo, create a static method
named 'new':
static new (...args)
{ return new this (...args);
}
Use it like this:
Foo.new("world").hello();
This way I hide the "clunkiness" inside
this static method 'new()'.
Note that this method new() is generic,
it will work as is also
when inherited to sub-classes. If you need
to customize it in a subclass you can first call:
super.new(...args)
and then add any other stuff you need in the
method in a subclass, before returning its result.
A recapped working "one-line" solution for ES6: explained
The answer posted above by Bergi is basically correct.
TLDR; skip to the end 😎 for the one-liner solution
Bergi's answer may seem a unclear when reading it. So, here is a more expanded code-sample that illustrates TWO new ES6 features to achieve the desired goals.
Together, they let a single function C (below) provide the dual-role of a factory and new-able fn; which constructs a B inst that derives from a A.
The B constructor utilizes super handling to invoke the A constructor with initialization arguments. In our final #3 - #4 examples constructed by C.
The A constructor demonstrates the semantics of the new.target psuedo-var to discover new was actually invoked with B.
First, we will make use of ES6 new.target psuedo-var that gives us the RHS of a new RHS() expression.
Technically, we could have gotten new.target as this?.__proto__?.constructor; they are equivalent.
Second, we will make use of ES6 Reflect.construct. Which is crucial to working around the ES6 class constructor invocation constraints; if we are bound and determined to not use new RHS(...).
Test the following and see for yourself its output (also provided in #1-4 below).
class A {
constructor(...a) {
const descendentType = new.target;
console.log(`A's constructor seeing 'new' invoked on ${descendentType?.name} with args: %o`,a);
}
}
class B extends A {
constructor(...a) {
super(...a);
}
}
// C is our DUAL mode Factory
function C(...a) {
console.log(`C's new.target => ${new.target?.name}`);
const inst = new.target ? Reflect.construct(B, a) : new B(...a);
console.log(`C has constructed a ${inst.__proto__.constructor.name} inst`);
return inst;
}
Which we can then invoke it in the following ways:
new A('NEW-A()')
output => "A's constructor seeing 'new' invoked on A with args: ['NEW-A()']"
new B('NEW-B()')
output => "A's constructor seeing 'new' invoked on B with args: ['NEW-B()']"
new C('NEW-C()')
output => "C's new.target => C"
output => "A's constructor seeing 'new' invoked on B with args: ['NEW-C()']"
output => "C has constructed a B inst"
C('PLAIN-C()')
output => "C's new.target => undefined"
output => "A's constructor seeing 'new' invoked on B with args: ['PLAIN-C()']"
output => "C has constructed a B inst"
Where #3 and #4 achieve the originally desired goals.
The simplified `C` looks like:
function C(...a) {return Reflect.construct(B, a);}
OR - if 3rd arg of Reflect.construct not utilized for init.
function C(...a) {return new B(...a);}
Beware: C must be a function not a class for this to both be allowed, and to work returning an alternate this on a new C() invocation, etc.
Also to circumvent strict mode rules for arguments.callee requires using a closure (smalltalk-block. Illustrated below:
class B extends A {
// embedding within a class and generically referencing it requires =>
static C = (() => {
const $class = this; return function(...a) {
return Reflect.construct($class, a);}})();
// Read more on `Reflect.construct` 3rd argument to see more capabilities
// for why it does MORE than just `new $class(...a)` would do.
}
exports.C = B.C;
⛐⚠️⛐ You could do some awful things like fiddle the __proto__ on the resulting inst and change out its constructor and name. Which would make it look and feel like a real subclass C of B depending on how far you want to go to manipulate the object-model. The subtleties abound in what happens with getters/setters, super and # privates. But for much of that you can STAY ES6 CLEAN and get clever with using extends and providing a template superclass flattened mixin tree; which I do a lot of in efekt for supporting tiny-but-complete µhtml reactive custom-elements parts and related PWA app models and responsive dynamic just-in-time versioned code bundling from EdgeS ESS backend servers. As in ... const M = $class => class extends $class {...}.
My motivations...
I posted this to help explain the semantics and a working ES6 solution, which is what I use to support subclassing Promise to provide FutureValue with better workflow handling capabilities in my github efekt library (EdgeS Front End Kit library).
In 2022, with ES6 onwards you can do it with the static method that can be called before the instance of the class is created, to create a instance of the class.
So the code should look something like this:
class Foo {
constructor(x) {
this.x = x;
}
//static class
static Init(x) {
return new Foo(x)
}
sayHello() {
return `hello ${this.x}`;
}
}
//so if i call
Foo.Init('world').sayHello();
//it prints: hello world
But if you are doing all this to make a chain of method you can also look at the following construct:
function MyName(name) {
if (this instanceof MyName) {
this.name = name,
this.prepend = function(n) {
this.name = `${n} ${this.name}`;
return this;
}
,
this.append = function(n) {
this.name = `${this.name} ${n} `;
return this;
}
,
this.show = function() {
return this.name;
}
} else {
return new MyName(name);
}
}
//Call
MyName('vinod').prepend('dev').append('hacks').show();
//prints: dev vinod hacks
The method above returns this at the end of each method which makes the object, properties & method avaialble.
The good part is these methods can be used again & again to create a sentence as
MyName('vinod').prepend('dev').append('hacks')
.prepend("the").append('javascript').append('for Stackoverflow').show();
I have used it as a stringBuilder or to generate xml dynamically.
Calling the class constructor without the new keyword is not possible.
The error message is quite specific.
See a blog post on 2ality and the spec:
However, you can only invoke a class via new, not via a function call (Sect. 9.2.2 in the spec):
> Point()
TypeError: Classes can’t be function-called
I'm adding this as a follow up to a comment by naomik and utilizing on the method illustrated by Tim and Bergi. I'm also going to suggest an of function to use as a general case.
To do this in a functional way AND utilize the efficiency of prototypes (not re-create all method each time a new instance is created), one could use this pattern
const Foo = function(x){ this._value = x ... }
Foo.of = function(x){ return new Foo(x) }
Foo.prototype = {
increment(){ return Foo.of(this._value + 1) },
...
}
Please note that this is consistent with fantasy-land JS specs
https://github.com/fantasyland/fantasy-land#of-method
I personally feel that it is cleaner to use the ES6 class syntax
class Foo {
static of(x) { new Foo(x)}
constructor(x) { this._value = x }
increment() { Foo.of(this._value+1) }
}
Now one could wrap this in a closure as such
class Foo {
static of(x) { new _Foo(x)}
constructor(x) { this._value = x }
increment() { Foo.of(this._value+1) }
}
function FooOf (x) {
return Foo.of(x)
}
Or rename FooOf and Foo as desired, ie the class could be FooClass and the function just Foo, etc.
This is better than place the class in the function because creating new instances doesn't burden us with creating new classes as well.
Yet another way is to create a an of function
const of = (classObj,...args) => (
classObj.of
? classObj.of(value)
: new classObj(args)
)
And then do something like of(Foo,5).increment()
Still finding interesting ways to use instanceof without relying on new or class keywords. In this example program, we compute the 100,000th fibonacci number in less than one second. The result is over 20,000 digits long -
const fib = x =>
Loop // <- no `new`
( (n, a, b) =>
n <= 0n
? String(a) // <- no `new`
: Recur(n - 1n, b, a + b) // <- no `new`
, BigInt(x) // <- no `new`
, 0n
, 1n
)
function Loop (f, ...init)
{ let r = f(...init)
while (r instanceof Recur) // <- instanceof works
r = f(...r)
return r
}
function Recur (...v)
{ return Object.create // <- not a class, but works
( Recur.prototype // <- set prototype
, { constructor: { value: Recur } // <- set constructor
, [Symbol.iterator]: { value: _ => v.values() } // <- whatever you want
}
)
}
document.body.textContent = fib(100000)
body { overflow-wrap: anywhere; }
I don't know why I haven't thought of this before -
function atom (T, v)
{ return Object.assign
( Object.create
( T.prototype
, { constructor: { value: T } }
)
, v
)
}
function pair (car, cdr)
{ return atom(pair, { car, cdr }) }
const p =
pair(1, 2)
console.log(p)
console.log(p instanceof pair)
Output -
{
"car": 1,
"cdr": 2
}
true
I wrote a small helper function which solves this problem. It effectively converts an ES6 class into an older ES5 constructor function which isn't subject to the same ruleset. This way you can create constructors which don't need new. You can also overload constructors in a similar way to the builtin Number, String etc.
function callableConstructor(c, f) {
function ret(...args) {
if(new.target) {
return new c(...args)
}
return f(...args)
}
ret.prototype = c.prototype
ret.prototype.constructor = ret
return ret
}
Test it below:
function callableConstructor(c, f) {
function ret(...args) {
if(new.target) {
return new c(...args)
}
return f(...args)
}
ret.prototype = c.prototype
ret.prototype.constructor = ret
return ret
}
// Usage
class Foo {
constructor(a, b) {
this.a = a
this.b = 2 * b
}
f() {
return this.a + this.b
}
}
Foo = callableConstructor(Foo, (...args) => new Foo(...args))
let foo = new Foo(2, 3)
console.log(foo) // Foo { a: 2, b: 6 }
console.log(foo.f()) // 8
console.log(foo instanceof Foo) // true
foo = Foo(2, 3)
console.log(foo) // Foo { a: 2, b: 6 }
console.log(foo.f()) // 8
console.log(foo instanceof Foo) // true
I came at this issue because I encountered the no-new "do not use new for side effects" eslint rule - which turns out it's a bad practice to use new for an object that is immediately discarded.
I still wanted to use the class syntax because I like it, but I agree that a regular class with new keyword for something that does not produce an object can be confusing.
The solution for me was simple. Define an unexported class in a module and export a function that instatinates it.
class SideEffects {
constructor() {
}
// ...
}
export function addSideEffects() {
// eslint-disable-next-line no-new
new SideEffects();
}
Yes, we are still using the new keyword, but it's used internally in the module and it's obvious from reading the module file that it's not a regular class - and the exported function also makes it clear that it does not create an object.
This might be a little contrived, but it works
function Foo(x){
"use strict"
class Bar {
constructor(x) {
if (!(this instanceof Bar)) return new Bar(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
return new Bar(x)
}
Foo("world").hello()
You can't use a class without the new constructor, in my case I didn't want to use the new constructor any time I wanted to use my class, so what you can do is to wrap your class as follows (in my case it's a Dates utils library):
const defaultOptions = {
defaultFormatOptions: 'dd/MM/yyyy'
}
class DatesClass {
constructor(date = new Date(), options) {
this.date = date
this.options = { ...defaultOptions, ...options }
}
get value() {
return this.date
}
add() {}
...
}
export default (date, options) => new DateClass(date, options)
// then you can use it as follow
import dates from 'path/to/yourClass/from/above'
dates(new Date()).add({ unit: 'day', qty: 2}).value

Casting from JSON in Typescript not working

Given the following classes
class A {
constructor(){
this.name ="Some name";
}
name:string;
}
class C extends A {
get Age() {
return 21;
}
SayHello(){
return "Hello";
}
}
If you would to build the OBJECT from a JSON Parse
var demo2:C= JSON.parse('{"name":"Joan of Arc"}') AS C;
This will not work:
console.log(demo2.Age);
console.log(demo2.SayHello());
Any workaround or ideas?
It doesn't work because Typescript doesn't cast JS objects, meaning that it doesn't change or modify them, it's only used for types. So when you use as statement, demo2 is being treated by Typescript as instance of C, while in reality demo2 isn't instance of C.
To make it work you can modify C so it has a constructor which accepts an object and assigns its properties to this
// add this to the body of C
constructor(obj: C) {
Object.assign(this, obj);
}
// later in code
const demo2 = new C(JSON.parse('{"name":"Joan of Arc"}') AS C);
JSON.parse(...) as AnyClass will not (cast) or create the object AnyClass.
One clever solution are:
const parsedJson = JSON.parse(...)
const myObj = new AnyClass();
Object.assign(myObj, parsedJson);

How to implement this C++ pattern in Javascript?

A method from an inherited class should return the object type from who has inherited. In C++ this behaviour is easy to accomplish. But I don't know how to do it in javascript. I know it is wrong but I wrote like this.
class A {
someMethod() {
return new A();
}
}
class B extends A {
}
var b = new B();
b.someMethod() // should return an object of type B not A
in C++ this is easy to do
template <typename c>
struct a
{
a() : _value(NULL) {}
a(std::string v) : _v(v) {}
static c* from_string(std::string &v)
{
return new c(v);
}
private:
std::string _v;
};
struct b : public a<b>
{
b() : b<a>() {}
b(std::string &v) : node<b>(a) {}
};
How should this be implemented using javascript?
edit
This is not how inherits a class, is a particular pattern of inheriting and creating objects. There are several examples like Buffer.from, Buffer.alloc from Node.Js. But I would like to reproduce this from a base class.
A guy showed me that my issue could be solved using the following script:
class A {
method() { return this.constructor(); }
}
class B {}
var b = new B();
var b1 = b.method();
What I really would like to do is something like following.
class A {
static from() { return new this.constructor() }
};
class B extends A {};
a = A.from();
b = B.from();
a instanceof A // should be true
b instanceof B // should be true.
edit 2
I found something.
I found in typescript the same C++ behaviour can be archived as follows:
class a {
static from<t extends a>(c: { new(): t }) : t {
return new c();
}
};
class b extends a {
}
let b1 = a.from(b);
b1 instanceof b
b1 instanceof a
console.log(b1);
the es6 equivalent is:
class a {
static from(c) {
return new c();
}
}
;
class b extends a {
}
let b1 = a.from(b);
b1 instanceof b;
b1 instanceof a;
console.log(b1);
//# sourceMappingURL=index.js.map
As I've commented: a template class in C++ is actually a metaclass. It is used for constructing other classes out of it.
So we can apply this observation to JavaScript. I've played around and here's the closest thing I could get. First define a "template":
function TemplateA(cls) {
class A {
static from() {
return new cls();
};
foo() {
return -1;
};
};
return A;
};
Now define custom "extends":
function Extends(base, derived) {
// Update statics
// (these should not be overwritten)
var common = {name: 1, prototype: 1, length: 1};
var statics = Object.getOwnPropertyNames(base)
.filter(el => !common[el]);
statics.forEach(el => {
derived[el] = base[el];
});
// Update instance methods
var instanceMethods = Object.getOwnPropertyNames(base.prototype);
instanceMethods.forEach(el => {
derived.prototype[el] = base.prototype[el];
});
};
and finally usage:
class B {
test() { return 1; }
};
> Extends(TemplateA(B), B);
> var b = B.from();
> b instanceof B;
true
> var x = new B();
> x.foo();
-1
> x.test();
1
It seems to do what you want. This has some drawbacks though. It is not really an inheritance (the prototype is just updated). In particular B is not a subclass of A<B> (actually no such class even exists after Extends). On the other hand JavaScript's inheritance/prototyping is quite unique and very different from C++ and so we can't expect everything to work.
Side notes:
Is it safe? Probably. However it does require lots of discipline from a dev. For example it is too easy to overwrite something you didn't want to.
Would I use it in prod environment? Unlikely. Whatever you are trying to accomplish most likely can be achieved in some other, standard way. Treat the solution as an academic fun.
Finally: who told you that C++ way is the best way? Your swimming skills are not really useful when you are climbing, right? So I strongly suggest you rethink your entire architecture and try to do things differently.

Dynamical inheritance TypeScript

JavaScript permit dynamical inheritance. I was wondering if TypeScript take it into account. The following code might illustrate the problem.
// inheritance.js
function fn1() {
this.a = "fn1";
}
function fn2() {
// ...
}
let f1 = new fn1(); // "instance" of fn1
let f2 = new fn2(); // "instance" of fn2
// inheritance
f2.__proto__ = f1;
// f2.a inherits from f1
console.log(f2.a); // output: "fn1"
As you can see we add an object f1, which is an instance of fn1, in the prototype chain of f2.
My question is therefore the following: can we reproduce this behave in TypeScript by using classes?
How would I change the following code to have the expected output?
// inheritance.ts
class class1 {
public a: string = "class1";
}
class class2 extends class1 {
// ...
}
let c1 = new class1();
let c2 = new class2();
console.log(c1.a); // output: "class1"
// this line would not work
c2.__proto__ = c1;
// change value c1.a
c1.a = "dynamical inheritance test";
console.log(c2.a); // should print value of c1.a (i.e "dynamical inheritance test")
I think what you are looking for is like an intersection mixing. There's a simple example found at the typescript docs. To do what you want, you, you can basically just assign the mixing's resulting class to the to inheriting class, then copy all properties of the class you want to be the extending to the result:
function extendDynamic<T, U>(first: T, second: U): T & U {
let result = <T & U>{};
(<any>result) = (<any>first);
for (let it in second) {
if (second.hasOwnProperty(it)) {
(<any>result)[it] = (<any>second[it]);
}
}
return result;
}
class Class1 {
public a: string;
constructor(n: string) {
this.a = n;
}
}
class Class2 {
b: string = 'bbb';
}
const a = new Class1("bar");
const b = extendDynamic(a, new Class2());
a.a = 'foo';
console.log(b.a, b.b); // foo, bbb

Extend native JavaScript array

Is there any way to inherit a class from JS native function?
For example, I have a JS function like this:
function Xarray()
{
Array.apply(this, arguments);
//some stuff for insert, add and remove notification
}
Xarray.prototype = new Array();
I tried to convert it to Typescript but i failed!!
export class Xarray implements Array {
}
The compiler asks me to define all Array interface properties. I know if I need this Xarray.prototype = new Array();, I have to extend Array in TS.
How to extend the JS native object in TS?
Starting in TypeScript 1.6, you can extend the Array type, see What's new in TypeScript
Here's an example:
class MyNewArray<T> extends Array<T> {
getFirst() {
return this[0];
}
}
var myArray = new MyNewArray<string>();
myArray.push("First Element");
console.log(myArray.getFirst()); // "First Element"
If you are emitting to ES5 or below, then use the following code:
class MyNewArray<T> extends Array<T> {
constructor(...items: T[]) {
super(...items);
Object.setPrototypeOf(this, MyNewArray.prototype);
}
getFirst() {
return this[0];
}
}
Read more about why this is necessary here.
I don't think there is a way to inherit existing interfaces like Array,
export class Xarray implements Array {
}
You should create a function and inherit it with its prototype. Typescript also will accept it which is similar to javascript.
function Xarray(...args: any[]): void; // required in TS 0.9.5
function Xarray()
{
Array.apply(this, arguments);
// some stuff for insert, add and remove notification
}
Xarray.prototype = new Array();
UPDATE: This one is discussed well and provided the best solution for this at jqfaq.com.
//a dummy class it to inherite array.
class XArray {
constructor() {
Array.apply(this, arguments);
return new Array();
}
// we need this, or TS will show an error,
//XArray["prototype"] = new Array(); will replace with native js arrray function
pop(): any { return "" };
push(val): number { return 0; };
length: number;
}
//Adding Arrray to XArray prototype chain.
XArray["prototype"] = new Array();
//our Class
class YArray extends XArray {
///Some stuff
}
var arr = new YArray();
//we can use the array prop here.
arr.push("one");
arr.push("two");
document.writeln("First Elemet in array : " + arr[0]);
document.writeln("</br>Array Lenght : " + arr.length);
Hope, this might help you!!!
Yes it's possible to extend a native JS object in TS, however there is an issue extending built-in types (those included in lib.d.ts) like Array. Read this post for workaround: http://typescript.codeplex.com/workitem/4
So defining a type interface which extends a native type object at a later stage can be done in the following way:
/// <reference path="lib.d.ts"/>
interface Array {
sort: (input: Array) => Array;
}
Using on a concrete example, you can sort some elements on an array which define a sort function in an interface and later implements it on an object.
class Math implements Array {
sort : (x: Array) => Array {
// sorting the array
}
}
var x = new Math();
x.sort([2,3,32,3]);
While researching this, I came across Ben Nadel's excellent post on Extending JavaScript Arrays While Keeping Native Bracket-Notation Functionality. After some initial confusion on how to succesfully convert this into TypeScript, I created a fully working Collection class that can be subclassed.
It can do everything an Array can, including indexing by brackets,use in loop constructions (for, while, forEach), maps, etc.
The main implementation points are
Create an array in the constructor, add the methods to the array and return that from the constructor
Copy dummy declarations of Array methods to pass the implements Array bit
Example of usage:
var foo = new Foo({id : 1})
var c = new Collection();
c.add(foo)
c.length === 1; // => true
foo === c[0]; // => true
foo === c.find(1); // => true
I made it available as a gist, complete with tests and an example implementation of a subclass, but I present the full source here:
/*
* Utility "class" extending Array with lookup functions
*
* Typescript conversion of Ben Nadel's Collection class.
* https://gist.github.com/fatso83/3773d4cb5f39128b3732
*
* #author Carl-Erik Kopseng
* #author Ben Nadel (javascript original)
*/
export interface Identifiable {
getId : () => any;
}
export class Collection<T extends Identifiable> implements Array<T> {
constructor(...initialItems:any[]) {
var collection = Object.create(Array.prototype);
Collection.init(collection, initialItems, Collection.prototype);
return collection;
}
static init(collection, initialItems:any[], prototype) {
Object.getOwnPropertyNames(prototype)
.forEach((prop) => {
if (prop === 'constructor') return;
Object.defineProperty(collection, prop, { value: prototype[prop] })
});
// If we don't redefine the property, the length property is suddenly enumerable!
// Failing to do this, this would fail: Object.keys([]) === Object.keys(new Collection() )
Object.defineProperty(collection, 'length', {
value: collection.length,
writable: true,
enumerable: false
});
var itemsToPush = initialItems;
if (Array.isArray(initialItems[0]) && initialItems.length === 1) {
itemsToPush = initialItems[0];
}
Array.prototype.push.apply(collection, itemsToPush);
return collection;
}
// Find an element by checking each element's getId() method
public find(id:any):T;
// Find an element using a lookup function that
// returns true when given the right element
public find(lookupFn:(e:T) => boolean):T ;
find(x:any) {
var res, comparitor;
if (typeof x === 'function') {
comparitor = x;
} else {
comparitor = (e) => {
return e.getId() === x;
}
}
res = [].filter.call(this, comparitor);
if (res.length) return res[0];
else return null;
}
// Add an element
add(value:T);
// Adds all ements in the array (flattens it)
add(arr:T[]);
add(arr:Collection<T>);
add(value) {
// Check to see if the item is an array or a subtype thereof
if (value instanceof Array) {
// Add each sub-item using default push() method.
Array.prototype.push.apply(this, value);
} else {
// Use the default push() method.
Array.prototype.push.call(this, value);
}
// Return this object reference for method chaining.
return this;
}
remove(elem:T):boolean;
remove(lookupFn:(e:T) => boolean):boolean ;
remove(x:any):boolean {
return !!this._remove(x);
}
/**
* #return the removed element if found, else null
*/
_remove(x:any):T {
var arr = this;
var index = -1;
if (typeof x === 'function') {
for (var i = 0, len = arr.length; i < len; i++) {
if (x(this[i])) {
index = i;
break;
}
}
} else {
index = arr.indexOf(x);
}
if (index === -1) {
return null;
}
else {
var res = arr.splice(index, 1);
return res.length ? res[0] : null;
}
}
// dummy declarations
// "massaged" the Array interface definitions in lib.d.ts to fit here
toString:()=> string;
toLocaleString:()=> string;
concat:<U extends T[]>(...items:U[])=> T[];
join:(separator?:string)=> string;
pop:()=> T;
push:(...items:T[])=> number;
reverse:()=> T[];
shift:()=> T;
slice:(start?:number, end?:number)=> T[];
sort:(compareFn?:(a:T, b:T) => number)=> T[];
splice:(start?:number, deleteCount?:number, ...items:T[])=> T[];
unshift:(...items:T[])=> number;
indexOf:(searchElement:T, fromIndex?:number)=> number;
lastIndexOf:(searchElement:T, fromIndex?:number)=> number;
every:(callbackfn:(value:T, index:number, array:T[]) => boolean, thisArg?:any)=> boolean;
some:(callbackfn:(value:T, index:number, array:T[]) => boolean, thisArg?:any)=> boolean;
forEach:(callbackfn:(value:T, index:number, array:T[]) => void, thisArg?:any)=> void;
map:<U>(callbackfn:(value:T, index:number, array:T[]) => U, thisArg?:any)=> U[];
filter:(callbackfn:(value:T, index:number, array:T[]) => boolean, thisArg?:any)=> T[];
reduce:<U>(callbackfn:(previousValue:U, currentValue:T, currentIndex:number, array:T[]) => U, initialValue:U)=> U;
reduceRight:<U>(callbackfn:(previousValue:U, currentValue:T, currentIndex:number, array:T[]) => U, initialValue:U)=> U;
length:number;
[n: number]: T;
}
Of course, the bits on Identifiable, the find and remove methods are not needed, but I supply them none the less as a full fledged example is a tad more usable than a bare-bones Collection without any methods of its own.
Constructors that return an object implicitly substitute the value of this for callers of super(). Generated constructor code has to capture whatever super() returns and replace it with this.
Built-in classes use ES6 new.target to do the fixup but there's no way for ES5 code to ensure that new.target has a value calling the constructor.
This is why your extra methods vanish - your object has the wrong prototype.
All you need to do is fix the prototype chain after calling super().
export class RoleSet extends Array {
constructor() {
super();
Object.setPrototypeOf(this, RoleSet.prototype);
}
private containsRoleset(roleset:RoleSet){
if (this.length < roleset.length) return false;
for (var i = 0; i < roleset.length; i++) {
if (this.indexOf(roleset[i]) === -1) return false;
}
return true;
}
public contains(item: string | RoleSet): boolean {
if (item) {
return typeof item === "string" ?
this.indexOf(item) !== -1 :
this.containsRoleset(item);
} else {
return true;
}
}
}
Be aware that this curse shall afflict thy children and thy children's children until the end of code; you have to do the fixup in every generation of an inheritance chain.
In your case, a good bet would be to use this pattern:
function XArray(array) {
array = array || [];
//add a new method
array.second = function second() {
return array[1];
};
//overwrite an existing method with a super type pattern
var _push = array.push;
array.push = function push() {
_push.apply(array, arguments);
console.log("pushed: ", arguments);
};
//The important line.
return array
}
Then you can do:
var list = XArray([3, 4]);
list.second() ; => 4
list[1] = 5;
list.second() ; => 5
note however that:
list.constructor ; => Array and not XArray
If you already have a working Xarray implementation, I don't see the point in recreating it in typescript, which eventually will compile back to JavaScript.
But I do see the point in being able to use the Xarray in TypeScript.
In order to accomplish this, you simply need an interface for your Xarray. You don't even need to have a concrete implementation of your interface since your existing js implementation will serve as one.
interface Xarray{
apply(...arguments : any[]) : void;
//some stuff for insert, add and ...
}
declare var Xarray: {
new (...items: any[]): Xarray;
(...items: any[]): Xarray;
prototype: Array; // This should expose all the Array stuff from ECMAScript
}
After doing this, should be able to use your custom defined type through the declared variable without actually implementing it in TypeScript.
var xArr = new Xarray();
xArr.apply("blah", "hehe", "LOL");
You might look for reference here to see how they typed the ECMAScript Array API:
http://typescript.codeplex.com/SourceControl/changeset/view/2bee84410e02#bin/lib.d.ts
Yes you can augment the Builtin types and do it in a way that doesn't require all the paraphernalia of an XArray as described in the other answers and is closer to how you would do it in javascript.
Typescript allows a number of ways to do this, but for the Builtin types like Array and Number you need to use "merging" and declare the global namespace to augment the types, see the docs
so for Array we can add an optional metadata object and a get first member
declare global {
interface Array<T> {
meta?: any|null ,
getFirst(): T
}
}
if(!Array.prototype.meta )
{
Array.prototype.meta = null
}
if(!Array.prototype.getFirst )
{
Array.prototype.getFirst = function() {
return this[0];
}
}
we can use this like so:
let myarray: number[] = [ 1,2,3 ]
myarray.meta = { desc: "first three ints" }
let first: number = myarray.getFirst()
The same goes for Number say I want to add a modulo function that isn't limited like the remainder %
declare global {
interface Number {
mod(n:number): number
}
}
if(!Number.prototype.mod )
{
Number.prototype.mod = function (n: number) {
return ((this % n) + n) % n;
}
}
and we can use it like so:
let foo = 9;
console.log("-9.mod(5) is "+ foo.mod(5))
For Functions that we may want to add an API to ie to make it behave like a function and an object we can use hybrid types (see docs)
// augment a (number) => string function with an API
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
//helper function to get my augmented counter function with preset values
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
use it like so:-
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
With purpose to overcome the problem of extension of the native Array class, I took advantage of a decorator.
function extendArray(constructor: Function) {
Object.getOwnPropertyNames(constructor.prototype)
.filter(name => name !== 'constructor')
.forEach(name => {
const attributes = Object.getOwnPropertyDescriptor(constructor.prototype, name);
Object.defineProperty(Array.prototype, name, attributes);
});
}
#extendArray
export class Collection<T> extends Array<T> {
constructor(...args: T[]) {
super(...args);
}
// my appended methods
}
BTW This decorator can be made more generic (for other native classes) if to use a decorator factory.
Don't know how frowned upon this is but for example I needed to create an array of BulletTypes so that I could cycle through them. What I did is the following:
interface BulletTypesArray extends Array<BulletType> {
DefaultBullet?: Bullet;
}
var BulletTypes: BulletTypesArray = [ GreenBullet, RedBullet ];
BulletTypes.DefaultBullet = GreenBullet;
Obviously you could could also make a generic interface, something like interface SuperArray<T> extends Array<T>.

Categories

Resources