Issue
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!
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.
Answered By - Ry-
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.