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;- ✓Correct answer: With a conditional type using
inferon the patternSet<infer T> - 2With indexed access
(typeof ids)[number] - 3With the
ElementType<typeof ids>utility from the standard library
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.