Created
December 3, 2016 20:08
-
-
Save jens1101/6932bb5627366f8cd8c578ef585d9d15 to your computer and use it in GitHub Desktop.
How to store a class reference in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class Node { | |
| //... | |
| } | |
| export class UnidirectionalNode extends Node { | |
| private next: Node; | |
| //... | |
| } | |
| export class BidirectionalNode extends Node { | |
| private next: Node; | |
| private previous: Node | |
| //... | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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