How do I take in a console input from a user in TypeScript?
For example, in Python I would use:
userInput = input("Enter name: ")
What is the equivalent in TypeScript?
You can use the readline
node module. See readline in node documentation.
To import readline in TypeScript use the asterisk(*
) character.
For example:
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 only adds optional static typing and transpilation capabilities to JavaScript. It's a purely compile-time artifact; at runtime, there is no TypeScript, which is why this question is about JavaScript, not TypeScript.
If you're talking about accepting input from the console, you're probably talking about a node.js application. In Reading value from console, interactively, the solution is to use 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() + "]");
});
In the browser, you would use a prompt:
var userInput = prompt('Please enter your name.');
On Node you can use 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();
});
If anyone is looking for an updated and concise version...
I'm using the 'readline' package, so start with yarn add readline
or npm i readline
.
First, put this in a separate file (ie "question.ts")
import {createInterface} from "readline";
const rl = createInterface({
input: process.stdin,
output: process.stdout
});
const question = (questionText: string) =>
new Promise<string>(resolve => rl.question(questionText, resolve))
.finally(() => rl.close());
export default question;
and then
import question from "./question"
const name = await question("What is your name?");
const answer = await question("Are you sure? (y/N) ")
.then(answer => answer.toLowerCase() == 'y')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With