我有一个用 JavaScript 编写的旧项目,我只需将其重命名为 .ts
即可将其“转换”为 TypeScript。
一切正常,但我不知道如何为以下示例分配类型:
function test(userid: number) {
var that = this;
this.UserId = userid;
//this.UserId : number = userid; //Not Working
}
test.prototype.load = () => {
var id = this.UserId;
}
我不知道如何将 TypeDefinition 分配给本地 UserId
变量。这只是一个简单的例子。我的项目非常大,我无法重构整个项目。
最佳答案
我不知道如何将类型分配给 this.UserId
。我不认为,你可以做到这一点,因为这就是 class
es 的用途。
在 TypeScript 中你可以这样写:
class test {
public UserId: number;
constructor(userid: number) {
this.UserId = userid;
}
public load = () => {
let id = this.UserId;
}
}
翻译为:
var test = (function () {
function test(userid) {
var _this = this;
this.load = function () {
var id = _this.UserId;
};
this.UserId = userid;
}
return test;
})();
如果您没有资源来重写您的应用程序,那么我会简单地选择:
function test(userid: number) {
this.UserId = userid; // Don't add type here ...
}
test.prototype.load = () => {
var id = this.UserId as number; // ... add type here
}
虽然没有那么强大,但总比没有好。
关于javascript - TypeScript 在 JavaScript 函数中为 this.varName 分配类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33518086/