typescript - How to fill properties of class TypeScript?
问题描述
Lets assume there is a model class like:
class Filter implements IFilterJournal {
public category: number;
public subject: number;
public teacher: number;
public mark: number;
}
I can create instance of this class:
let f = new Filter();
It returns object Filter
with empty properties inside.
How to fill properties of class more convenient?
I can determine consturctor like:
public constructor(public category: number, public subject: number, public teacher: number, public mark: number){
}
Then at the time of creation instance pass parameters:
let f = new Filter(1, 2, 3, 4)
But what if I need to fill only public subject: number;
property? either
others? How to fill them selectively?
Another was is to make parameters as optional:
public constructor(public category?: number, public subject?: number, public teacher?: number, public mark?: number){}
Then use this like:
let f = new Filter(subject = 1);
解决方案
如果您可以使用任何属性组合初始化对象,则可以使用构造函数Partial<Filter>
作为参数,并用于Object.assign
设置对象上的字段。
class Filter {
constructor(data: Partial<Filter>){
Object.assign(this, data);
}
public category: number;
public subject: number;
public teacher: number;
public mark: number;
}
new Filter({ category: 0})
new Filter({ category: 1, subject: 2, teacher: 3, mark: 4})
Note Partial
是一种映射类型,它保留一个类型的成员,但将所有成员标记为Partial
. 请参阅文档。在这种情况下Partial<Filter>
相当于:
interface PartialFilter{
category?: number;
subject?: number;
teacher?: number;
mark?: number;
}
如果您的类型有方法,Partial
将允许构造函数的参数包含这些方法,这可能是一个问题。您可以使用条件类型从参数中过滤掉方法,但这有点复杂:
type NotFunctions<T> = { [P in keyof T]: T[P] extends Function ? never : P }[keyof T];
class Filter {
constructor(data: Partial<Pick<Filter, NotFunctions<Filter>>>){
Object.assign(this, data);
}
public category: number;
public subject: number;
public teacher: number;
public mark: number;
public sayHi(){ return "Hi" }
}
new Filter({ category: 0, sayHi: ()=> {}}) //Error with new constructor argument type
new Filter({ category: 0})
new Filter({ category: 1, subject: 2, teacher: 3, mark: 4})
推荐阅读
- apache-spark - spark结构化流批处理数据刷新问题(按子句分区)
- firebase - 我在“应用引擎”应用程序中收到一些未知请求,想知道它们是什么
- python - 为什么即使指定了 Y lim,Matplotlib 条形图也会切出高值?
- html - 在方形空间中调整 iframe 的大小以适应任何屏幕尺寸
- typescript - 具有静态工厂的抽象父类的子类的类型
- flutter - 即使在颤振应用程序窗口之外如何获得鼠标位置
- dataframe - 当数据位于两个不同的数据帧中时,如何显示阴影错误带?
- php - 使用相同的短代码返回多个结果
- c# - 方法参数类型来处理具有不同键类型的字典?
- json - 解码 JSON Bool ......我做错了什么?