Typescript 中的备用函数重载?

Alternate function overloading in Typescript?

该语言的一个未记录的功能似乎是使用管道运算符来重载参数。

示例:

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

在下面的案例之前似乎工作正常。我的问题是 (1) 继续以这种方式使用管道操作员是否安全? (2) 如果是这样,我该如何解决下面的情况?

 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;
 }

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(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;
 }