Using Window prompt() method with TypeScript

Updated: February 14, 2024 By: Guest Contributor Post a comment

Introduction

TypeScript, a superset of JavaScript, enhances development by adding static type definitions, which can improve code quality and readability. One common method available in the browser’s Window object is prompt(), used to display a dialogue for user input. This technique, when combined with TypeScript’s typing capabilities, unlocks powerful patterns for collecting and using user input in a safe, predictable manner.

In this post, we’ll explore how to effectively use the prompt() method within TypeScript, gradually moving from basic implementations to more advanced scenarios. We’ll cover the basic syntax, handling user input, type assertions, and more complex use cases involving custom types and interfaces.

Basic Usage of prompt() in TypeScript

The prompt() method displays a dialogue box that prompts the visitor for input. A basic usage of prompt in TypeScript looks something like this:

let userInput: string | null = prompt('Please enter your name:');

This code displays a dialogue asking for the user’s name. Note the type annotation string | null; this is because prompt() returns a string if the user inputs something, or null if the dialogue is canceled.

Handling User Input

Once you have the user input, it’s important to handle it appropriately. A simple pattern involves checking if the input is not null and then proceeding with further actions:

if (userInput !== null) {
    console.log(`Hello, ${userInput}!`);
} else {
    console.log('User did not provide a name.');
}

This ensures that we only proceed with the intended behavior when we receive valid input from the user.

Type Assertions with prompt()

There may be cases where you’re expecting a specific type of input from the user, such as a number. TypeScript’s type assertions can be handy here:

let userAge: number = Number(prompt('Please enter your age:'));
if (!isNaN(userAge)) {
    console.log(`You are ${userAge} years old.`);
} else {
    console.log('Please enter a valid number.');
}

This example attempts to convert the user’s input into a number. The isNaN() function is then used to check if the conversion was successful before proceeding.

Using prompt() with Custom Types and Interfaces

As your TypeScript applications grow more complex, you may find yourself needing more structured data from user input. Consider this scenario where we use an interface to represent a user:

interface User {
    name: string;
    age: number;
}

function getUserInput(): User {
    let name: string | null = prompt('Enter your name:');
    let ageStr: string | null = prompt('Enter your age:');
    let age: number = Number(ageStr);

    if (name && !isNaN(age)) {
        return {name, age};
    } else {
        throw new Error('Invalid input');
    }
}

This function prompts the user twice to gather name and age, which it then uses to construct and return a User object. Note how TypeScript’s static typing helps ensure the structure of the returned object matches the User interface, enhancing the predictability and reliability of your code.

Advanced Example: Combining prompt() with Generic Functions

For more advanced use cases, you might want to create reusable functions that can prompt for any type of input. This can be achieved using TypeScript’s generics. Here’s how such a function might look:

function promptForInput<T>(message: string, converter: (input: string) => T): T {
    let input: string | null = prompt(message);
    if (input === null) {
        throw new Error('User cancelled the prompt.');
    }
    return converter(input);
}

// Usage
let userAge: number = promptForInput('Please enter your age:', Number);
console.log(`You are ${userAge} years old.`);

This generic function promptForInput takes a message to display and a converter function that transforms the input string into the desired type. If the user cancels the prompt, it throws an error; otherwise, it returns the converted value. This pattern is highly reusable and can adapt to various input types and conversion needs.

Conclusion

Working with the prompt() method in TypeScript helps leverage the robustness of static typing while interacting with users through the browser’s dialogue system. From handling simple strings to employing complex types and custom conversion functions, TypeScript’s capabilities enable developers to write clearer, more predictable code. Through careful handling of the resulting data, incorporating user feedback into your applications can enhance user experience and provide valuable insights into user preferences.