Home > OS >  What's the proper way to fix this type error?
What's the proper way to fix this type error?

Time:05-06

What's the proper way to fix this? I don't want to just cast or make a copy of the array, converting undefined to an empty string or something like this. I guess it's hacky. What's the proper way to fix this?

Type 'ProcessEnv' is not assignable to type '{ [key: string]: string; }'.
  'string' index signatures are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.ts(2322)
node-pty.d.ts(45, 5): The expected type comes from property 'env' which is declared here on type 'IPtyForkOptions | IWindowsPtyForkOptions'

code:

import { IPty, spawn } from 'node-pty';

    ptyProcess = spawn(shell, [], {
      name: 'xterm-color',
      cols: 80,
      rows: 30,
      cwd: process.env.HOME,
      env: process.env // error comes from this assignment
    });

EDIT 1:

Currently I'm doing this:

interface INonUndefinedEnv {
  [key: string]: string
}

const safeEnv = () => {
  let o:INonUndefinedEnv = {};
  for(const [key, value] of Object.keys(process.env).entries())
      o[key] = value ?? ""; // make sure it's string and never undefined
  return o;
}

then I can do:

ptyProcess = spawn(shell, [], {
  name: 'xterm-color',
  cols: 80,
  rows: 30,
  cwd: process.env.HOME,
  env: safeEnv() // type match
});

But I'd like to avoid all this loop if possible...

CodePudding user response:

I think the way you did it is not hacky. It's the right thing to do. The hacky thing to do would be to look into node-pty's source code to see if undefined values could cause an issue and using "as any" if they couldn't. :)

CodePudding user response:

Based on the interface and the error given you would need to do this:

    import { IPty, spawn } from 'node-pty';

    ptyProcess = spawn(shell, [], {
      name: 'xterm-color',
      cols: 80,
      rows: 30,
      cwd: process.env.HOME,
      env: { myEnv: process.env }
    });

And you could change "myEnv" to whatever.

  • Related