Home > Software design >  How can I create an instance of an array declared via a type in TypeScript?
How can I create an instance of an array declared via a type in TypeScript?

Time:12-05

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:

  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!

CodePudding user response:

You just return something that looks like the type you specified, so i.e. you can return

return [[1, 2, 3]]

or

return []

or

return [[]]

but not

return [1]

or

return [["abc"]]

There's no need to use new Array, just create and return something like shown above.

CodePudding user response:

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.

  • Related