如何采取在控制台输入从打字稿用户?
例如,在Python我会用:
userInput = input("Enter name: ")
什么是打字稿等价?
您可以使用readline
节点模块。见readline节点文档。
要导入的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();
});
在浏览器中,你可以使用一个提示:
var userInput = prompt('Please enter your name.');
在节点可以使用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();
});
打字稿只加入了可选的静态类型和transpilation功能的JavaScript。这是一个纯粹的编译时神器;在运行时,没有打字稿,这就是为什么这个问题是关于JavaScript的,而不是打字稿。
如果你在谈论接受从控制台输入,你可能是在谈论一个Node.js应用程式。在Reading value from console, interactively,解决的办法是使用标准输入:
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() + "]");
});
它实际上取决于你输入元件使用的HTML元素。通常情况下,你可以通过使用prompt()
与window
对象的帮助下读取输入。在点击确定,返回结果是什么用户输入值,返回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);