简体   繁体   中英

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

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...

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. :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM