0

I am attempting to use TS 2.8's TextDecoder interface to convert a Uint8Array to string for purposes of displaying an image in a web UI. The method I'm attempting to use is below:

  displayImage(image: Uint8Array): string {
    var fileString = new TextDecoder("utf-8").decode(image);
    return 'data:image/jpeg;base64,' + fileString;
  }

When I try to compile I receive "'TS2304: Cannot find name 'TextDecoder'".

I'm running TS 2.8 so according to this what I'm trying should work using the built-in interface. Is this a case of needing to define a provider? Any help appreciated.

EDIT: tsconfig.json below:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
christok
  • 1,087
  • 2
  • 12
  • 29

1 Answers1

0

First, make sure that you include the "dom" lib in your tsconfig. If you provide your tsconfig, it might be easier to determine.

Secondly, your data URI expects base64 encoded output, not JPEG bytes decoded as UTF-8 (if it is even valid UTF-8). See this question for how to do that.

Third, if you're trying to display a Uint8Array as a jpeg image, a Blob might be a better way to do it (code was hand-written and not tested):

var blob = new Blob([image], {
    type: 'image/jpeg'
});

var url = URL.createObjectURL(blob);

return url;
  • Thanks. I did check tsconfig.json previously. Updated original post to include file contents. Your other ideas are probably relevant to my final solution, but would not throw the build error, yes? – christok Aug 17 '18 at 01:12
  • Correct. However, I just copied that function and tsconfig into a new project alone and it compiled just fine. What build error are you seeing? – Jonathon Richardson Aug 17 '18 at 01:16
  • "'TS2304: Cannot find name 'TextDecoder'" - I'm glad it's not just my code! – christok Aug 17 '18 at 01:19
  • Run `tsc --version` (or whatever path to your compiler) to make sure you're using the correct version of Typescript. You might have installed 2.8 in your project but are using a globally installed compiler or vis/versa. Similarly, if you are using vscode, there's a button in the lower right hand corner with Typescript and a version. By default, VSCode uses an embedded version of TS, rather than the one installed with your project. You can click that button to tell it to do otherwise. You can run `./node_modules/.bin/tsc` to get the version of typescript in the repo. – Jonathon Richardson Aug 17 '18 at 01:26
  • Yes, in fact tsc --version showed 2.1 but I've resolved that and am not getting 2.8. Will keep researching because it seems promising. – christok Aug 17 '18 at 15:10