繁体   English   中英

修复此类型错误的正确方法是什么?

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

解决这个问题的正确方法是什么? 我不想只是转换或复制数组,将undefined转换为空字符串或类似的东西。 我想这很hacky。 解决这个问题的正确方法是什么?

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'

代码:

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
    });

编辑 1:

目前我正在这样做:

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;
}

然后我可以这样做:

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

但如果可能的话,我想避免所有这些循环......

我认为你这样做的方式并不骇人听闻。 这是正确的做法。 棘手的事情是查看 node-pty 的源代码,看看未定义的值是否会导致问题,如果不能,则使用“as any”。 :)

根据界面和给定的错误,您需要这样做:

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

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

您可以将“myEnv”更改为任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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