我有一个未定义的类属性,因为它没有被转换为js:
打字稿代码:
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
透明代码:
"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
您可以看到对象'属性'没有被翻译,因此循环不起作用。为什么这样以及如何强制适当的翻译?
答案 0 :(得分:3)
如果您希望对象不是undefined
:
class User {
public properties: {
gender: string
name: string
first_name: string
last_name: string
email: string
fb_id: string
} = <any> { };
TypeScript不会猜测您要初始化哪些类属性以及您不想要的属性。