简体   繁体   English

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

[英]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.我不想只是转换或复制数组,将undefined转换为空字符串或类似的东西。 I guess it's hacky.我想这很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:编辑 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.棘手的事情是查看 node-pty 的源代码,看看未定义的值是否会导致问题,如果不能,则使用“as any”。 :) :)

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.您可以将“myEnv”更改为任何内容。

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

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