首页 > 解决方案 > 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);

标签: typescripttypescript2.0

解决方案


如果您可以使用任何属性组合初始化对象,则可以使用构造函数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})

推荐阅读