You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Inquirer的CLI中实现按键监听?自定义Prompt编译报错求助

问题:Inquirer CLI中实现Ctrl+V快捷键支持

我用TypeScript基于Inquirer开发了一个CLI工具,但无法实现Ctrl+V快捷键的粘贴功能。我发现@inquirer/core里有useKeypress方法,但不知道如何在常规的input prompt中使用,我的代码如下:

const answer = await inquirer.prompt([
  {
    type: 'input',
    name: 'question',
    message: 'Insert something:',
    validate: function (value: string) {
      if (!value) {
        return "You must insert something.";
      }
      return true;
    },
  },    
]);

编辑内容

感谢@jsejcksn的帮助,我创建了以下自定义prompt类:

import {
  createPrompt,
  useState,
  useKeypress,
  usePrefix,
  isEnterKey,
  isBackspaceKey,
  AsyncPromptConfig,
} from '@inquirer/core';
import type {} from '@inquirer/type';

type InputConfig = AsyncPromptConfig & {
  default?: string;
  transformer?: (value: string, { isFinal }: { isFinal: boolean }) => string;
};

export default createPrompt<string, InputConfig>((config, done) => {
  const [status, setStatus] = useState('pending');
  const [defaultValue, setDefaultValue] = useState<string | undefined>(config.default);
  const [errorMsg, setError] = useState<string | undefined>(undefined);
  const [value, setValue] = useState('');

  const isLoading = status === 'loading';
  const prefix = usePrefix(isLoading);

  useKeypress(async (key, rl) => {
    // Ignore keypress while our prompt is doing other processing.
    if (status !== 'pending') {
      return;
    }

    if (isEnterKey(key)) {
      const answer = value || defaultValue || '';
      setStatus('loading');
      const isValid = await config.validate(answer);
      if (isValid === true) {
        setValue(answer);
        setStatus('done');
        done(answer);
      } else {
        // TODO: Can we keep the value after validation failure?
        // `rl.line = value` works but it looses the cursor position.
        setValue('');
        setError(isValid || 'You must provide a valid value');
        setStatus('pending');
      }
    } else if (isBackspaceKey(key) && !value) {
      setDefaultValue(undefined);
    } else {
      setValue(rl.line);
      setError(undefined);
    }
  });

  const message = config.message;
  let formattedValue = value;
  if (typeof config.transformer === 'function') {
    formattedValue = config.transformer(value, { isFinal: status === 'done' });
  }

  let defaultStr = '';
  if (defaultValue && status !== 'done' && !value) {
    defaultStr = ` (${defaultValue})`;
  }

  let error = '';
  if (errorMsg) {
    error = `> ${errorMsg}`;
  }
  return [`${prefix} ${message}${defaultStr} ${formattedValue}`, error];
});

但编译时出现以下错误:

  • error TS2345: 类型“{ type: string; name: string; message: string; validate: (value: string) => true | "Il valore non può essere nullo."; }[]”的参数不能赋给类型“InputConfig”的参数。类型“{ type: string; name: string; message: string; validate: (value: string) => true | "You must insert something."; }[]”中缺少属性“message”,但类型“AsyncPromptConfig”中需要该属性。
  • error TS2339: 类型“string”上不存在属性“question”。该错误出现在尝试获取问题的answer时。

内容的提问来源于stack exchange,提问作者Filippo1980

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:01:44