【发布时间】:2016-02-24 20:01:39
【问题描述】:
如何在 TypeScript 中接收来自用户的控制台输入?
例如,在 Python 中我会使用:
userInput = input("Enter name: ")
TypeScript 中的等价物是什么?
【问题讨论】:
-
您是指运行 CLI 应用程序时的控制台还是 google chrome 开发控制台时的控制台?
标签: typescript
如何在 TypeScript 中接收来自用户的控制台输入?
例如,在 Python 中我会使用:
userInput = input("Enter name: ")
TypeScript 中的等价物是什么?
【问题讨论】:
标签: typescript
您可以使用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();
});
【讨论】:
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() + "]");
});
【讨论】:
在浏览器中,您会使用提示符:
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();
});
【讨论】:
import * from "readline";
灵感来自@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'
【讨论】:
这实际上取决于您使用哪个 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);
【讨论】: