2015-05-03 2 views
1

Я играл с типами union в TypScript 1.4, и я столкнулся с ошибкой несоответствия ложного типа.Typescript 1.4 Типы соединений, неверная ошибка ложного типа

Является ли это ошибкой компилятора или что-то не хватает?

ошибка TS2345: Аргумент типа 'строка | Object 'не присваивается параметру типа' string '. Тип 'Объект' не присваивается типу 'string'.

/** @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); 
    } 

} 

ответ

3

Машинопись компилятор не знает ваши намерения с 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); 
    } 
} 
+0

совершенен, что я искал утверждение типа/литья. Благодарю. – user634545

+1

Это не литье. С заявлением не выполняется проверка времени выполнения. –

+0

Я вижу, отсюда и название ... – user634545

Смежные вопросы