I am writing a type declaration file for a library I do not control. One of the methods accepts an array of strings as a parameter, but these strings can only be very specific values. Currently I am typing this parameter as a string[]
, but I was wondering if there was a way to enhance this to include the specific values as well.
Example source (I cannot change this):
Fruits(filter) {
for (let fruit of filter.fruits)
{
switch(fruit)
{
case 'Apple':
...do stuff
case 'Pear':
...do stuff
default:
console.error('Invalid Fruit');
return false;
}
}
return true;
}
My current type declaration:
function Fruits(filter: FruitFilter): boolean;
interface FruitFilter {
fruits: string[];
}
As I was writing this question I came up with a partial solution by defining a union type of the strings that are valid, then setting the type of the field to an array of that union rather than an array of strings. This gives me the checking I want, but I noticed that if you enter an invalid string, it marks all of the strings in the array as invalid with the error Type 'string' is not assignable to type 'Fruit'
. Is there a better way of doing this so that only the offending string is marked as invalid, or is this as close as I'm going to get?
Partial solution:
function Fruits(filter: FruitFilter): boolean;
type Fruit = 'Apple' | 'Pear'
interface FruitFilter {
fruits: Fruit[];
}
foo
, the other is typefoo[]
. – Plain