[英]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;
}
我的问题是(1)以这种方式继续使用管道运算符是否安全?
是。 这是设计使然。
(2)如果是,该如何解决以下情况?
您需要一个用户定义的类型保护功能。 这是固定代码:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.