类属性没有得到transpiled

问题描述:

我有一个类属性,它是不确定的,因为它不是transpiled到JS:类属性没有得到transpiled

打字稿代码:

import * as _ from "lodash" 

/** 
* User 
*/ 
class User { 

    public properties: { 
     gender: string 
     name: string 
     first_name: string 
     last_name: string 
     email: string 
     fb_id: string 
    } 

    constructor(data) { 

     _.forOwn(data, (value: string, key: string) => // Needs fat arrow to bind 'this' 
     { 
      if (value) { this.properties[ key ] = value } 
     }) 

    } 

    public useProperties() { 
     return this.properties 
    } 
} 

export default User 

Transpiled代码:

"use strict"; 
var _ = require("lodash"); 
var User = (function() { 
    function User(data) { 
     var _this = this; 
     _.forOwn(data, function (value, key) { 
      if (value) { 
       _this.properties[key] = value; 
      } 
     }); 
    } 
    User.prototype.useProperties = function() { 
     return this.properties; 
    }; 
    return User; 
}()); 
Object.defineProperty(exports, "__esModule", { value: true }); 
exports.default = User; 
//# sourceMappingURL=user_model.js.map 

你可以看到对象的'属性'没有被转换,因此循环无法工作。为什么是这样以及如何强制适当的翻译?

你需要自己初始化对象,如果你希望它是不是undefined

class User { 

    public properties: { 
     gender: string 
     name: string 
     first_name: string 
     last_name: string 
     email: string 
     fb_id: string 
    } = <any> { }; 

打字稿不猜测要被初始化类的属性,哪些是你不知道。

+0

谢谢,你会如何用'as'语法替换? –

+2

@RobertBrax'= {};任何;'' –