Skip to content

Instantly share code, notes, and snippets.

@jens1101
Created December 3, 2016 20:08
Show Gist options
  • Select an option

  • Save jens1101/6932bb5627366f8cd8c578ef585d9d15 to your computer and use it in GitHub Desktop.

Select an option

Save jens1101/6932bb5627366f8cd8c578ef585d9d15 to your computer and use it in GitHub Desktop.
How to store a class reference in Typescript
export class Node {
//...
}
export class UnidirectionalNode extends Node {
private next: Node;
//...
}
export class BidirectionalNode extends Node {
private next: Node;
private previous: Node
//...
}
import {Node, UnidirectionalNode, BidirectionalNode} from './Node.ts';
/**
* Creates an array of the specified Node type with the specified length
* @param NodeType This is a new-able type that inherits from the class `Node` in some way
* @param {number} length The size of the array
*/
function createArray(NodeType: { new(): Node }, length: number): Node[] {
let arr:Node[] = [];
for(let i=0; i < length; i++) {
arr[i] = new NodeType();
}
return arr;
}
let foo = createArray(UnidirectionalNode, 2); //Ok
let bar = createArray(BidirectionalNode, 12); //Ok
let bar = createArray(Node, 1); //Ok
let asdf = createArray(Number, 3); //Error!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment