TypeScript · Senior · Question 31 of 75

How do you get the element type of a Set<T> or Map<K, V> from a value?

const ids = new Set(['a', 'b']);
type Id = typeof ids extends Set<infer T> ? T : never;

Explanation

Set has no numeric index signature, so [number] doesn't work. A conditional type with infer extracts the parameter of any generic: Map<infer K, infer V>, Promise<infer R>. There's no built-in ElementType utility. Here Id is string.

Further reading

Problem with a question

TypeScript · Senior · question 31

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz