我一直在玩Typescript 1.4中的联合类型,并且遇到了错误的类型不匹配错误。
这是编译器错误还是我缺少什么?
错误TS2345:“字符串|类型”参数 无法将“对象”分配给“字符串”类型的参数。类型“对象”不能分配给类型“字符串”。
/** @inheritdoc */
public log(logLevel : LogLevel, message : string|Object, exception?: Exception): void {
// Check if the message is of type Object
if (Util.isObject(message)) {
// Log the message object
this.logObject(logLevel, message, exception);
}
// Check if the message is of type string
else if(Util.isString(message)) {
// Log the message
this.logMessage(logLevel, message, exception);
}
}
class Util {
protected static TYPE_STRING = 'string';
public static isString(object : any): boolean {
return (typeof object === Util.TYPE_STRING);
}
public static isObject(object : any): boolean {
return (object instanceof Object);
}
}
打字稿编译器不知道您对isString
和isObject
方法的意图,并且不能正确地传递类型。您应该内联类型测试:
/** @inheritdoc */
public log(logLevel : LogLevel, message : string|Object, exception?: Exception): void {
// Check if the message is of type Object
if (message instanceof Object) {
// Log the message object
this.logObject(logLevel, message, exception);
}
// Check if the message is of type string
else if (typeof message === 'string') {
// Log the message
this.logMessage(logLevel, message, exception);
}
}
如果您不想这样做,可以断言类型:
/** @inheritdoc */
public log(logLevel : LogLevel, message : string|Object, exception?: Exception): void {
// Check if the message is of type Object
if (Util.isObject(message)) {
// Log the message object
this.logObject(logLevel, <Object> message, exception);
}
// Check if the message is of type string
else if(Util.isString(message)) {
// Log the message
this.logMessage(logLevel, <string> message, exception);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句