假设我有一个 TypeScript 类,其属性名为 birthDate
和基于此属性的 3 个 getter:year
、month
和 天
。
class User {
birthDate: Date;
get month(): number {
return this.birthDate.getMonth();
}
get year(): number {
return this.birthDate.getFullYear();
}
get day(): number {
return this.birthDate.getDay();
}
}
我可以实例化一个User
,设置一个birthDate
并正常使用getter。
const user = new User();
user.birthDate = new Date();
console.log(user.year, user.month, user.day);
但是,显然,我不能直接设置年份,因为我只有一个 getter(而不是 setter)
// this does not work as expected
user.year = 2022
另一方面,当我尝试使用普通对象定义 User
时,TypeScript 编译器会生成一个错误,指出我缺少属性 (year
, 月
和日
):
// this does not works... why?
const user: User = {
birthDate: new Date()
}
我的问题是:为什么我应该在普通对象中定义这些属性,因为它们只是 getter?在这种情况下,如何使用普通对象创建用户
?
工作代码here
最佳答案
当你写的时候
const user: User = {
birthDate: new Date()
}
您没有创建User
对象。您只需创建一个具有属性birthDate
的对象。该对象不满足 User
声明所隐含的接口(interface),因为它没有属性 month
、year
和 day
.
你知道 Javascript 并没有真正的类吗?它只有对象。在纯旧的 Javascript 中,不是 class
声明,有人写道
function User(birthDate) {
this.birthDate = birthDate;
}
User.prototype.getYear = function () {
return this.birthDate.getYear();
}
User.prototype.getMonth = function () {
return this.birthDate.getMonth();
}
User.prototype.getDay = function () {
return this.birthDate.getDay();
}
var user = new User(new Date());
一个函数,这里的User()
可以充当构造函数,当使用new
调用它时,会使用类的prototype
创建一个对象code> 对象作为原型(prototype)(实际上,它是通过对象的 __proto__
属性链接的)。
class
声明只是旧模式的语法糖。
关于javascript - 使用普通对象创建实例时需要 TypeScript getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71163250/