typescript - 当对象在 TypeScript 中实现某些接口时,为对象定义新的属性和方法
问题描述
在 OOP 中,除了在类实现的接口中声明的属性之外,还允许定义新属性:
interface IIncapsuledData {
propertyA: number;
propertyB: string;
}
class TestClass implements IIncapsuledData {
public constructor(private incapsuledData: IIncapsuledData) { }
public get propertyA(): number { return this.incapsuledData.propertyA; }
public get propertyB(): string { return this.incapsuledData.propertyB }
// we can defined new getter without declaring new type alias or interface
public get newComputedProperty(): string {
return `${this.propertyA}__${this.propertyB}`;
}
}
我们可以对普通对象做同样的事情吗?
const objectWithoutClass: IIncapsuledData = {
propertyA: 2,
propertyB: 'b',
// Error! Object literal may only specify known properties.
get newComputedProperty(): string {
return `${this.propertyA}__${this.propertyB}`;
}
}
知道解决方案
声明新接口
interface IComputedData extends IIncapsuledData {
readonly newComputedProperty: string;
}
const objectWithoutClass: IComputedData = {
propertyA: 2,
propertyB: 'b',
get newComputedProperty(): string {
return `${this.propertyA}__${this.propertyB}`;
}
}
缺点:与类案例不同,我需要声明新接口。日常工作变得更多。一些优雅的解决方案,比如课堂案例?
解决方案
您可以使用相交类型,并与索引器相交:
interface IEncapsuledData {
propertyA: number;
propertyB: string;
}
const objectWithoutClass: IEncapsuledData & { [key: string]: any } = {
propertyA: 1,
propertyB: '2',
propertyC: 3
};
推荐阅读
- javascript - 事件委托和循环遍历 if 语句中的元素
- wordpress - WordPress评论表单自动完成关闭
- node.js - Discord Bot 在使用 args 运行命令后意外返回“无效命令”错误消息
- asp.net-core - 由于 dotnet ef dbcontext --json 失败,无法在 Visual Studio 2019 中列出实体框架迁移
- sql - 将 STRING_AGG 转换为 FOR XML PATH
- java - 如何将 bean 加载到测试上下文中?
- javascript - Javascript 中的画布仅在没有其他 html 代码时才有效
- ios - UIImage 到 CIImage 到 UIImage 导致 pngData 在 iOS 12 上返回 nil
- ruby-on-rails - 从 Rails 中错误消息的开头删除字段名称?
- c++ - 模板模板参数场景