#"no overload matches this call" using a Set

4 messages · Page 1 of 1 (latest)

shrewd marlin
#

I managed to write this code which seems to work well (what it does is not the point here):

export function countUniqueValues<Type extends string|number = string>(values: Type[]): number {
  return new Set<Type>(values).size;
}

But my first attempt led to a "no overload matches this call" error:

export function countUniqueValues(values: string[]|number[]): number {
  return new Set(values).size; // Error TS2769
}

Can you explain why the second solution is not valid for TypeScript?

acoustic monolith
#

When you say new Set(values) without specifying the type parameter, you are asking it to infer an appropriate type parameter, and for whatever reason it is not smart enough to do this. By mousing over new Set you can see that it infers string and of course that won't work if values is a number[]. But it works if you tell it to use, say, new Set<string | number>(values).

#

Also, if you make countUniqueValues a bit more permissive and ask for (string | number)[] instead of string[] | number[], it infers just fine. But perhaps you want an error if someone tries to countUniqueValues([1, 'a'])

shrewd marlin
#

Exactly, for now I don't want mixed-type lists.