1

An undocumented feature of the language seems to be using the pipe operator to overload arguments.

Example:

 function foo(user : string | number) {
    //...
 }

Seems to be working fine until the case below. My question is (1) is it safe to continue to use the pipe operator this way? (2) if so, how can I fix the case below?

 function _isString<T>(value : T) : boolean { return typeof value === 'string'; };

 function foo(services : string | string[]) {

    //doesn't compile
    const aService : string[] = _isString(services) ? [services] : services;

    //but this does
    const bService : string[] = typeof services === 'string' ? [services] : services;
 }

1 Answer 1

1

My question is (1) is it safe to continue to use the pipe operator this way?

Yes. It is by design.

(2) if so, how can I fix the case below?

You need a user defined type guard function. Here is the fixed code:

 function _isString(value : any) : value is string { return typeof value === 'string'; };

 function foo(services : string | string[]) {

    // works
    const aService : string[] = _isString(services) ? [services] : services;

    // works
    const bService : string[] = typeof services === 'string' ? [services] : services;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm. Did not know about TS guard functions... guess the docs are very outdated.

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.