【问题标题】:Console input in TypeScriptTypeScript 中的控制台输入
【发布时间】:2016-02-24 20:01:39
【问题描述】:

如何在 TypeScript 中接收来自用户的控制台输入?

例如,在 Python 中我会使用:

userInput = input("Enter name: ")

TypeScript 中的等价物是什么?

【问题讨论】:

  • 您是指运行 CLI 应用程序时的控制台还是 google chrome 开发控制台时的控制台?

标签: typescript


【解决方案1】:

您可以使用readline 节点模块。请参阅节点文档中的readline

要在 TypeScript 中导入 readline,请使用星号 (*) 字符。 例如:

import * as readline from 'readline';

let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Is this example useful? [y/n] ', (answer) => {
  switch(answer.toLowerCase()) {
    case 'y':
      console.log('Super!');
      break;
    case 'n':
      console.log('Sorry! :(');
      break;
    default:
      console.log('Invalid answer!');
  }
  rl.close();
});

【讨论】:

  • @FredDanna 你是对的,但 TypeScript 只是一种在 NodeJS 代码上添加一层以添加类型检查等内容的语言。最后,编译后的 TypeScript 代码将生成 NodeJS 代码。换句话说,TypeScript 也是 NodeJS,因此您可以在 TypeScript 中使用任何 NodeJS 模块,包括 readline 模块。
【解决方案2】:

TypeScript 仅向 JavaScript 添加可选的静态类型和转换功能。它是一个纯粹的编译时工件;在运行时,没有 TypeScript,这就是为什么这个问题是关于 JavaScript,而不是 TypeScript。

如果您说的是接受来自控制台的输入,那么您可能说的是 node.js 应用程序。在Reading value from console, interactively,解决方法是使用stdin:

var stdin = process.openStdin();

stdin.addListener("data", function(d) {
    // note:  d is an object, and when converted to a string it will
    // end with a linefeed.  so we (rather crudely) account for that  
    // with toString() and then substring() 
    console.log("you entered: [" + d.toString().trim() + "]");
});

【讨论】:

    【解决方案3】:

    在浏览器中,您会使用提示符:

    var userInput = prompt('Please enter your name.');
    

    在 Node 上你可以使用Readline:

    var readline = require('readline');
    
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    rl.question("What do you think of Node.js? ", function(answer) {
      console.log("Thank you for your valuable feedback:", answer);
      rl.close();
    });
    

    【讨论】:

    • 我认为他想为 Node 写一个 TypeScript,我不确定 TypeScript 是否有类似import * from "readline";
    • @Akshay 确实如此!
    【解决方案4】:

    灵感来自@Elie G & @Fenton,一个随时可用的“readLine()”函数,如 swift、kotlin、C...

    async function readLine(): Promise<string> {
    
        const readLine = require('readline').createInterface({
            input: process.stdin,
            output: process.stdout
        });
    
        let answer = ""
        readLine.question("", (it: string) => { 
             answer = it
             readLine.close()
        })
        while (answer == "") { await sleep(100)  }
    
        return(answer)
    
    }
    
    // ——— Call
    
    async function aMiscFunction() {
    
        let answer = await readLine()
        console.log(answer)
    
    }
    
    /!\ if you call from a function, it must be declared 'async'
    

    【讨论】:

      【解决方案5】:

      这实际上取决于您使用哪个 HTML 元素作为输入元素。通常,您可以在window 对象的帮助下使用prompt() 读取输入。点击确定返回用户输入的值,点击取消返回null

      class Greeter {
      greet() {      
                alert("Hello "+this.getName())
          }
          getName() {
              return prompt("Hello !! Can I know your name..??" );;
          }
      }
      let greeter = new Greeter();
      let button = document.createElement('button');
      button.textContent = "Say Hello";
      button.onclick = function() {
         (greeter.greet());
      }
      document.body.appendChild(button);
      

      【讨论】:

      • 这个问题涉及 TypeScript,而不是客户端 JavaScript
      猜你喜欢
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多