27

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?

Fenton
  • 241,084
  • 71
  • 387
  • 401
WaterlessStraw
  • 613
  • 2
  • 9
  • 20
  • 3
    Do you mean the console as when running a CLI application or the console as the google chrome development console? – Pavlin Nov 22 '15 at 18:55

7 Answers7

29

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('...')).

Elie G.
  • 1,514
  • 1
  • 22
  • 38
  • 1
    @FredDanna You're right but TypeScript is just a language which adds a layer over NodeJS code to add things like type checks. At the end, your TypeScript code once compiled will generate NodeJS code. In other words, TypeScript is also NodeJS so you can use any NodeJS module in TypeScript including the readline module. – Elie G. Feb 28 '20 at 00:21
12

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();
});
Fenton
  • 241,084
  • 71
  • 387
  • 401
11

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() + "]");
});
Community
  • 1
  • 1
Marius Schulz
  • 15,976
  • 12
  • 63
  • 97
5

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')
Tomek
  • 607
  • 9
  • 16
2

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'
Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29
2

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!`)
-6

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);
Jeyanth
  • 531
  • 2
  • 6
  • 19