Angular typescript typecheck issues when importing tensorflow in web worker
Asked Answered
F

1

6

I am trying to use tensorflow/tfjs (TF) in a web-worker in an angular project.

Creating a web-worker using the ng generate worker command works just fine.

Importing TF in a component is fine too.

However importing TF in the worker i.e. :

import * as tf from '@tensorflow/tfjs'

Generates a bunch of missing definition errors when building through the ng build command. Missing types are typically DOM-related types such as error TS2304: Cannot find name ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement. Those types are used in some definitions in TF and, as I understand, those types are not accessible with web-workers because DOM manipulation cannot be done from workers. I am perfectly fine with that, my use of TF doesn't rely on those types. But I still need to find a way to build my worker.

I therefore tried to tinker with the tsconfig.worker.json file. My first attempt was to mimic the other tsconfig* files by adding "dom" in the compilerOptions.lib array :

["es2018", "webworker"] 

replaced by

["es2018", "webworker", "dom"]

This results in conflicting types definitions

error TS6200: Definitions of the following identifiers conflict with those in another file 

the webworker and dom libs have different definitions for the same types, but I can of course not remove the webworker lib reference.

My 2nd attempt was to add the skipTypeCheck compiler option in the tsconfig.worker.json file : That works just fine, I got TF running in my web worker and outputting results.

BUT...

Skipping type checking feels like ripping of the whole idea of using typescript. So my question is :

Is there a cleaner way to use TF in a webworker in angular while preserving type checking ?

Thanks for your anwsers. Please let me know if I should provide more configuration details.

Flawed answered 30/10, 2020 at 10:5 Comment(0)
P
0

From the official TensorFlow tutorial: https://www.tensorflow.org/js/tutorials/setup

When using TypeScript you may need to set skipLibCheck: true in your tsconfig.json file if your project makes use of strict null checking or you will run into errors during compilation.

This is better than skipTypeCheck as types in your code are still checked. This way the code compiles but you still get an error in console: Error when getting WebGL context: Error: Cannot create a canvas in this context.

But that is not a problem so far.

Peristome answered 25/11, 2020 at 15:59 Comment(1)
I actually don't use WebGL contexts, so your solution works just fine. ThanksFlawed

© 2022 - 2024 — McMap. All rights reserved.