looking for some solutions? You are welcome.

SOLVED: Typescript yells me that 'string | T[]' is not assignable to parameter of type 'ReadonlyArray

Joseph Wang:

I'm building a simple function called unique.

What this does is to remove all duplication from an array or string, so it has function overloading.

Please see this problem code example:

function unique(str: string): string[];
function unique<T>(arr: T[]): T[];

/**
 * Create an `array` without duplicates.
 */

function unique<T>(arrOrString: string | T[]): string[] | T[] {
  return [...new Set(arrOrString)]; // typescript will yell at me at this line.
}

export default unique;


enter image description here

enter image description here

However, if I change my code into if-else but actually do nothing, typescript now satisfy with this:


// same code, but actually compiling.

function unique(str: string): string[];
function unique<T>(arr: T[]): T[];

/**
 * Create an `array` without duplicates.
 */

function unique<T>(arrOrString: string | T[]): string[] | T[] {
  if (typeof arrOrString === 'string') {
    return [...new Set(arrOrString)];
  } else {
    return [...new Set(arrOrString)];
  }
}

export default unique;


Why is this happening? Do I have to write [...new Set(arrOrString)] twice in order to make it work?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent