Hi Blocklyites,
I recently started a new project using Blockly and React. I also wanted to try out using Typescript, which I am not very familiar with. Consequently, I used create-react-app with the '--template typescript' flag and then manually merged in the code from the blockly-react sample in blockly-examples. However, it seems that despite the existence of Typescript type files for Blockly (which I'm very grateful for) the Typescript compiler still wasn't happy.
Here is the relevant portion of the App.tsx file that the compiler wasn't happy with:
function App() {
const simpleWorkspace = React.createRef();
const generateCode = () => {
const code = BlocklyJS.workspaceToCode(
simpleWorkspace.current.workspace
);
console.log(code);
}
return (
<div className="App">
<button onClick={generateCode}>Convert</button>
<BlocklyComponent ref={simpleWorkspace}
readOnly={false} trashcan={true} media={'media/'}
Property 'workspaceToCode' does not exist on type 'typeof Generator'. TS2339
9 | const simpleWorkspace = React.createRef();
10 | const generateCode = () => {
> 11 | const code = BlocklyJS.workspaceToCode(
| ^
12 | simpleWorkspace.current.workspace
13 | );
14 | console.log(code);
To temporarily work around that I added a '// @ts-ignore' but then I got the following error:
Object is of type 'unknown'. TS2571
11 | // @ts-ignore
12 | const code = BlocklyJS.workspaceToCode(
> 13 | simpleWorkspace.current.workspace
| ^
14 | );
15 | console.log(code);
16 | }
I did a bit more research, tried a few more things, got a few more errors and eventually got to this point with the code:
function App() {
const simpleWorkspace: React.RefObject<BlocklyComponent> = React.createRef();
const generateCode = () => {
const currentWorkspace: BlocklyComponent = simpleWorkspace.current as BlocklyComponent;
// @ts-ignore
const code = BlocklyJS.workspaceToCode(currentWorkspace.workspace);
console.log(code);
}
return (
<div className="App">
<button onClick={generateCode}>Convert</button>
<BlocklyComponent ref={simpleWorkspace}
The above works, but I feel like I shouldn't have to explicitly type simpleWorkspace and I don't really like having to use 'as' in the definition of currentWorkspace (which otherwise causes a complaint that simpleWorkspace.current might be null. More importantly, though, I don't think I should have to completely ignore the type checking of the call to BlocklyJS.workspaceToCode.
I'm not sure if these are issues with the Blockly (and possibly React) Typescript type definitions or something else. Does anyone have any good ideas?
Thanks in advance.
-Mark