TypeScript - Types from arrays
Photo by Timothy Cuenat / Unsplash

TypeScript - Types from arrays

I found a frustration in the act of making arrays of acceptable values to use in input validation for closed lists when I'd already defined the same when setting the types. Could I find a way to set up the array once and use for both needs?

// setting up the type - TS can use this but not me.
type cowboy: string = "Good" | "Bad" | "Ugly"

const a_cowboy: cowboy = 'Not bad' // TS error because value not in type.

// Meanwhile in my run-time code I want to validate like this

// setting the array
const allowed_cowboys = ["Good", "Bad", "Ugly"]

// Use the array as a validator for some input 
if (allowed_cowboys.includes(inputCowboy){
  console.log('The saloon welcomes you')
}
else {
  console.log('No way Hose')
}

You can see in the above code we have to use the same list twice - for TS to do its magic in the editor but that won't help me at run-time, and once so I can validate the cowboys at the saloon door when the user enters them.

The answer is

 const cowboy_enum = ["Good", "Bad", "Ugly"] as const;
 type cowboy = typeof cowboy_enum[number];

const a_cowboy: cowboy = 'Not bad' // TS error because value not in type.

// Meanwhile in my run-time code I want to validate like this

// Use the cowboy_enum array as a validator for some input 
if (cowboy_enum.includes(inputCowboy){
  console.log('The saloon welcomes you')
}
else {
  console.log('No way Hose')
}

They look very similar but there's no duplication of the validation array! Saves code and reduces support concerns as there is only one place where we have to put the literals.

Thanks for reading.

VW Dec 2024