Fidel Seehawer
Aug 20, 2024

--

Perhaps a more suitable alternative:

type PredefinedFruits = "apples" | "oranges";

function selectFruit<T extends string>(fruit: T | PredefinedFruits) {

console.log(`You selected: ${fruit}`);

}

// Usage with predefined options

selectFruit("apples"); // Valid, and autocomplete will suggest "apples" and "oranges"

// Usage with any other string

selectFruit("bananas"); // Also valid, no autocomplete suggestion

--

--

Fidel Seehawer
Fidel Seehawer

Written by Fidel Seehawer

A father, husband, and software developer from the lovely city of Düsseldorf. With a passion for technology and a strong drive to constantly learn.

Responses (1)