Reputation: 31365
I have this function that should return a random item of an array.
function getRandomArrayItem {
return arr[Math.floor((Math.random()*arr.length))];
}
I'm gonna use it as follows:
const LANGUAGE_VALUES = ["EN","ES"] as const;
// I HAVE THIS TYPE
type LANGUAGE_VALUES_TYPE = typeof LANGUAGE_VALUES[number]; // THIS IS: "EN" | "ES"
// I NEED TO CALL getRandomArrayItem ON LANGUAGE_VALUES TO SELECTED A RANDOM LANGUAGE:
const language = getRandomArrayItem(LANGUAGE_VALUES);
I need the randomly selected language to be of the type LANGUAGE_VALUES_TYPE
. I.E: "EN" | "ES"
.
How can I do that?
Also, I would like it to be generic, cause I'll be using that function in other similar arrays, but with different content.
Upvotes: 1
Views: 190
Reputation: 10176
Using generics and typescript inference:
function getRandomArrayItem<T>(arr: T[]): T {
return arr[Math.floor((Math.random()*arr.length))];
}
const language = getRandomArrayItem(LANGUAGE_VALUES); // Language is now type of the content of LANGUAGE_VALUES array
In your example it is a bit trickier to cast LANGUAGE_VALUES
to the proper type. You need to first define the language type and then define the actual array, such as:
const VALUES_CONST = ["EN","ES"] as const;
type LANGUAGE_VALUES_TYPE = typeof VALUES_CONST[number];
const LANGUAGE_VALUES: LANGUAGE_VALUES_TYPE[] = ["EN","ES"]
const result = getRandomArrayItem<LANGUAGE_VALUES_TYPE>(LANGUAGE_VALUES)
// Result is of type 'EN' | 'ES'
Or force the casting:
const LANGUAGE_VALUES = ["EN","ES"] as const;
type LANGUAGE_VALUES_TYPE = typeof LANGUAGE_VALUES[number]; // THIS IS: "EN" | "ES"
const language = getRandomArrayItem(LANGUAGE_VALUES as unknown as LANGUAGE_VALUES_TYPE[]);
Upvotes: 1