2
votes

I am implementing this code from node js to typescript and I am having the following error

const StringPath:string = "../PathtoJson.json";

export class ClassName
{   
    name:string;
    constructor(name:string) {
        this.name = name;
    }
    loadn(filename:string) 
    {
        return new Promise((resolve, reject) => {
            let fs = require('fs');
                fs.readFile(filename, function (err:Error, data:any) 
                {
                    if (err) 
                    {
                        console.log(err);
                        reject();
                        throw err;   
                    }
                    let gg = JSON.parse(data);
                    resolve(data);
                });
            });
    }
}
let jsh = new ClassName("A string");
let  test = jsh.loadn(StringPath).then((result) => {
    test = JSON.parse(result); // here happens the error
    //return JSON.parse(result); // the same error happens here to
});

Error: (parameter) result: unknown

Argument of type 'unknown' is not assignable to parameter of type 'string'

4

4 Answers

7
votes

Function loadn is returning Promise<unknown>. It should return Promise<string> so you can type it as such.

  loadn(filename: string): Promise<string> { // Here
    return new Promise((resolve, reject) => {
      const fs = require("fs");
      fs.readFile(filename, function(err: Error, data: any) {
        if (err) {
          console.log(err);
          reject();
          throw err;
        }
        let gg = JSON.parse(data);
        resolve(data);
      });
    });
  }

Or type a Promise you're creating:

return new Promise<string>((resolve, reject) => {
0
votes

There is an issue in your code.

You should initialise result: any in success callback.

let test = jsh.loadn(StringPath).then((result: any) => {

It will work. I don't understand, why you are assigning test variable test =JSON.parse(result)

0
votes

For me it was only a IDE warning, there was actually no issue when I executed the code.

0
votes

I hade the same issue and I fixed this issue by doing

    const globalState: string | any = localStorage.getItem('globalState');
    return globalState!== null || globalState=== undefined ? JSON.parse(globalState) : undefined;

I have to cast my variable with string | any and then verifing if that variable is null or undefined before parsing it