TypeScript Tutorial
TypeScript User Input
readLine reads from the stdin box in the editor. Pair it with console.log so the user knows what to type.
readLine fills a variable
readLine() reads the next line from the stdin box at/typescript/try. It returns a string. Store that string, or convert it with Number when you need a number. This is StudyGrid’s input, not prompt() and not C++ cin.
Example
declare function readLine(): string;
console.log("Enter your age:");
const age: number = Number(readLine());
console.log("You entered " + age);The declare line tells tsc that readLine exists and returns a string. The editor provides the real function when the program runs. Sample stdin for this program: 20.
Click Try it in TypeScript. Type the input in the stdin box on the left, then compile. That box is what readLine() reads. The TypeScript editor uses tsc.
Always prompt with console.log
A program that waits on readLine() with no message looks frozen. Print a question first so the person at the keyboard knows what to type. On StudyGrid the answer is already in the stdin box before you compile, but the prompt still documents the program.
Example
declare function readLine(): string;
console.log("Price in euros:");
const price: number = Number(readLine());
console.log("Recorded: " + price);Sample stdin: 3.5. Change it and compile again.
Several values, several calls
Each readLine() takes one line. Call it twice for two values. Put each value on its own line in the stdin box. Spaces inside a line stay in the string; the next call does not start until the next line.
Example
declare function readLine(): string;
console.log("Enter two integers:");
const a: number = Number(readLine());
const b: number = Number(readLine());
console.log("sum is " + (a + b));Sample stdin for that program: two lines, 4 then 9. The first call gets4. The second call gets 9.
The type must match
readLine() always returns text. Number(readLine()) turns that text into anumber. If the line is hello, the result is NaN (not a number). Ask for the kind of value you declared, and test with matching stdin.
| You want | Typical stdin | How to store it |
|---|---|---|
| A whole number | 42 | Number(readLine()) |
| A decimal | 3.14 | Number(readLine()) |
| A word or sentence | Ada | readLine() as string |
A whole line, including spaces
readLine() reads until the end of the line. Spaces stay in the string. That is closer to C++getline than to cin >>, which stops at the first space. For a full name such asAda Lovelace, one call is enough.
Example
declare function readLine(): string;
console.log("Type a name:");
const name: string = readLine();
console.log("Hello, " + name);Do not use prompt(). Browsers use that for popups. Do not use cin. That is C++. On StudyGrid, input is readLine() plus the stdin box.
Output asks, input answers
console.log writes. readLine reads. Most interactive programs are that pair, repeated. Next: the types you can store in those variables.