【发布时间】:2019-06-15 18:37:50
【问题描述】:
我想知道在 TS 中使用访问器是否是一种好习惯,我是否正在测试用例,我注意到这样做会让你失去“鸭子打字”的“功能”。
是为了防止开发人员不必要的错误输入而设计的吗
还是我错过了什么?
class BlogPost {
constructor(private _title: string, private _summary: string,
private _hoverTitle?: string) {
}
public get title(): string {
return this._title;
}
public set title(value: string) {
this._title = value;
}
public get summary(): string {
return this._summary;
}
public set summary(value: string) {
this._summary = value;
}
public get hoverTitle(): string {
return this._hoverTitle;
}
public set hoverTitle(value: string) {
this._hoverTitle = value;
}
}
let blogPostItem: BlogPost;
blogPostItem = {
hoverTitle = '',
summary = '',
title = ''
}
这应该是一个有效的分配,但它显示了以下错误:
类型'{ title: string; 中缺少属性'hoverTitle'; _title:字符串;摘要:字符串; _摘要:任何; }' 但在 'BlogPost' 类型中是必需的。
当我尝试添加这些属性时,由于它们是私有的,它会显示此错误:
输入 '{ _hoverTitle: any; _摘要:任何; _title:任何;悬停标题:任何;摘要:任何;标题:任何; }' 不可分配给类型 'BlogPost'。 属性“_title”在“BlogPost”类型中是私有的,但在“{ _hoverTitle: any; _摘要:任何; _title:任何;悬停标题:任何;摘要:任何;标题:任何; }'。
这是有意为之还是我遗漏了什么?
Here is a live preview of the error
我认为这是处理问题的好方法! preview
只需让类实现一个接口,然后将接口用于“鸭子类型”...如果类已封装私有字段,这种方式无关紧要,因为您正在作为接口键入。
这来自@Titian Cernicova-Dragomir的答案...
【问题讨论】:
标签: typescript