0

I'm using TypeScript 2.9.2.

A 3rd party library URI.js has a static method declared as:

joinPaths(...paths: (string | URI)[]): URI;

Now I have a variable named urlPaths declared as urlPaths: string | string[], the following code is giving me error [ts] Expression expected. at the spread operator:

URI.joinPaths(typeof urlPaths === 'string' ? urlPaths as string : ...(urlPaths as string[]))

But if I extract the ternary operator expression out as a separate variable, it is fine:

const paths = typeof urlPaths === 'string' ? [urlPaths as string] : urlPaths as string[];
URI.joinPaths(...paths);

What's wrong with my syntax here?

1 Answer 1

1

Spread syntax is supported on arguments to functions, so your ... should be at the outer most level:

URI.joinPaths(... (typeof urlPaths === 'string' ? [urlPaths as string] : (urlPaths as string[])));

But also note that the asserions are redundant, typescript will figure out the type without them since typeof urlPaths === 'string' is a type guard and urlPaths: string | string[]

URI.joinPaths(... (typeof urlPaths === 'string' ? [urlPaths] : urlPaths));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.