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?
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';
const 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();
});
You can also use the readline's promises API (async/await) :
import * as readline from 'readline/promises';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
try {
// NOTE: the second parameter (the timeout) is optional.
const answer = await rl.question('Is this example useful? [y/n] ', {
signal: AbortSignal.timeout(10_000) // 10s timeout
});
switch(answer.toLowerCase()) {
case 'y':
console.log('Super!');
break;
case 'n':
console.log('Sorry! :(');
break;
default:
console.log('Invalid answer!');
}
} finally {
rl.close();
}
Note: the timeout is optional (e.g. await rl.question('...')
).
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();
});
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() + "]");
});
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')
Inspired from @Elie G & @Fenton, a ready to use "readLine()" function like in 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'
That should help you! lang: [PT-BR]
const prompt = require('prompt-sync')()
let nota1 = parseInt(prompt('digite a 1ª nota: '));
let nota2 = parseInt(prompt('digite a 2ª nota: '));
let nota3 = parseInt(prompt('digite a 3ª nota: '));
let media = (nota1+nota2+nota3)/3
if ((media >= 0)&&(media < 3)) {
console.log(`Sua média foi ${media.toFixed(1)}, seu resultado é: Reprovado!`)
} else if ((media>=3)&&(media < 7)) {
console.log(`Sua média foi ${media.toFixed(1)}, seu resultado é: Exame!`)
} else if ((media >=7)&&(media <=10)){
console.log(`Sua média foi ${media.toFixed(1)}, seu resultado é: Aprovado!`)
It actually depends on which HTML element you use as an input element. Normally, you can read the input by using prompt()
with the help of window
object. On clicking OK, it returns the value what user enters, returns null
on clicking Cancel.
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);