gpt4 book ai didi

typescript - 为什么 typescript 在将公共(public)参数编译为构造函数后创建重复赋值?

转载 作者:行者123 更新时间:2023-12-04 03:26:18 25 4
gpt4 key购买 nike

我是 typescript 的新手,正在玩编译。下面编译后的文件在js文件中有两个赋值,为什么会这样?

输入文件

class Student {
constructor(public fname: string){
this.fname = fname;
}
}

输出内容

var Student = /** @class */ (function () {
function Student(fname) {
this.fname = fname;
this.fname = fname;
}
return Student;
}());

最佳答案

TypeScript 包含一种从构造函数参数创建和分配类实例属性的简洁方法。

这意味着,而不是:

class TestClass {
public name: string;

constructor(name: string) {
this.name = name;
}
}

可以使用:

class TestClass {
constructor(public name: string) { }
}

在您的代码片段中,您混合了导致双重赋值的两种语法。

关于typescript - 为什么 typescript 在将公共(public)参数编译为构造函数后创建重复赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67514442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com