I have difficulties with typescript. One of my variable can have a string or array of string value. I would like to use a typeguard to use join function only on arrays. It looks like it ignores my condition.
Does anyone have an idea how to make a proper type narrowing here?
const x = (value: string | string[]) => {
return Array.isArray(value) ? value.join(',') : value
}
Typescript message:
Property ‘join’ does not exist on type ‘string | string[]’. Property ‘join’ does not exist on type ‘string’.ts(2339)
2
Even though you’re using Array.isArray(value) to check if value is an array, TypeScript might still be confused about the type because the type of value is string | string[].
To fix this, you can use TypeScript’s type assertion to explicitly tell the compiler that value is an array inside the if block. Here’s how you can adjust your function:
const x = (value: string | string[]): string => {
if (Array.isArray(value)) {
// TypeScript now knows `value` is `string[]`
return value.join(',');
} else {
// `value` is `string` here
return value;
}
}
By adding the if block, TypeScript can infer the type correctly.