Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create an instance of an array declared via a type in TypeScript?

If I start with this:

type Board = Array<Array<number>>;

Then this works fine to type-check when I pass boards around:

function boardWins(board:Board):boolean { ... }

But when I actually need to create a board, I wind up with this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  function createBoard():Board {
    // How can I just instantiate a Board? "new Board()" throws an error
    return new Array<Array<number>>();
  }

The return typing is fine, it’s the redundant redeclaration of the whole type in the "new" invocation that I want to avoid.

If I try new Board() I get:

'Board' only refers to a type, but is being used as a value here.

OK yes, constructors are functions and there is no Board function, but is there no syntactic sugar to allow this to avoid the redundancy and potential bugs of reinventing this wheel when I instantiate one of these?

Thanks for your help!

>Solution :

The value you’re making is just an empty array. All the rest of the syntax there is about giving it the type you want, which isn’t necessary when you’ve already declared the type.

function createBoard(): Board {
  return [];
}

And no, there’s no generic way to instantiate an arbitrary TypeScript type. That doesn’t really make sense with structural types.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading