0

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is helpful too but I accepted the answer that helped me get at the why of it a little more.
1

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.

1 Comment

I see... I think I see... Board is just a type check, and any array will satisfy it, unless TypeScript catches a whiff that I've manipulated it in some way that wouldn't fit the type restrictions. Since ultimately it's just an array and all I'm doing is intantiating it, there's nothing to go wrong. If I actually tried to put the wrong thing in it and then return it, the compiler would already be able to try to detect that because I declared the return type. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.