How to fill properties of class TypeScript?

typescript initialize class object
typescript class
typescript interface array
extend interface typescript
typescript override method
typescript interface default value
typescript readonly
typescript interface constructor

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);

If you can initialize the object with any combination of properties, you can use a constructor that takes Partial<Filter> as an argument, and uses Object.assign to set the fields on the object.

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 is a mapped type that keeps the members of a type but marks all of them as Partial. See docs. In this case Partial<Filter> is equivalent to:

interface PartialFilter{
    category?: number;
    subject?: number;
    teacher?: number;
    mark?: number;
}

If your type has methods, Partial would allow the argument to the constructor to contain those methods, this may be an issue. You can use conditional types to filter out methods from the argument, but it's a bit more complicated:

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})

[New Feature] Initialize Classes by Using an Object Initializer · Issue , Today when we initialize interface we get some hint of property that exist in this interface, Populate name and age var person = new Person { name: "foo", age: 10 }; @rihei bear in mind that classes in TypeScript do not play by any means the  When you declare a class in TypeScript, you are actually creating multiple declarations at the same time. The first is the type of the instance of the class.

Here's base solution :

class Filter implements IFilterJournal {

  public subject: number;

  // Define defaults 
  // Not need to complicate with constructor 
  private category: number = 0;
  private teacher: number = 0;
  private mark: number = 0;

  public constructor(subject: number) {

    if (typeof subject === 'number') {
      this.subject = subject;
    } else {
      console.error('Class error: Constructor parameter subject is not a number!');
    }

  }

  // Define setters
  public setCategory(category: number) {
    this.category = category;
  }

  public setTeacher(teacher: number) {
    this.teacher = teacher;
  }

  public setMark(mark: number) {
    this.mark = mark;
  }

  // Define getters
  public getCategory(): number {
    return this.subject;
  }

  public getTeacher(): number {
    return this.teacher;
  }

  public getMark(): number {
    return this.mark;
  }

  public getSubject(): number {
    return this.subject;
  }

}

Interfaces · TypeScript, In TypeScript, interfaces fill the role of naming these types, and are a powerful way you pass an object to a function that only has a couple of properties filled in. This is because when a class implements an interface, only the instance side  TypeScript is object oriented JavaScript. TypeScript supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Typescript gives built in support for this concept called class. JavaScript ES5 or earlier didn’t support classes.

You don't have to fill all the object properties right off that bat.

public constructor(public _category: number){
    category = _category;
}

Would work just fine. Just keep in mind that those properties you don't fill will be undefined if you call them later before assigning them, so at the very least you may want to initialize them to some sort of acceptable value. Perhaps:

public constructor(public _category: number){
    this.category = _category;
    this.subject = 0;
    this.teacher = 0;
    //etc...
}

Classes · TypeScript, This class has three members: a property called greeting , a constructor, and a inheritance feature: classes inherit properties and methods from base classes. TypeScript: Loop through properties of Class with Object.keys(this) gunjan1007 April 16, 2018 computers. Fill in your details below or click an icon to log in:

Utility Types · TypeScript, Constructs a type with all properties of T set to readonly , meaning the properties of the class C { x = 0; y = 0; } type T0 = InstanceType<typeof C>; // C type T1  In TypeScript, you can inherit a class from another class. Just use the extends keyword to perform inheritance. Consider the following example to understand it better.

Efficient Default Property Values in TypeScript, class Test { private label: string;. This is a TypeScript class with a property which we wish to have a default value. protected static SInit  By Example Introduction #. The purpose of this guide is to teach you how to write a high-quality definition file. This guide is structured by showing documentation for some API, along with sample usage of that API, and explaining how to write the corresponding declaration.

Class definitions in TypeScript, This section is a cheat sheet for class definitions in plain JavaScript. By default, all data slots in TypeScript are public properties. where each abstract method is a blank that has to be filled in (implemented) by subclasses. One of TypeScript’s core principles is that type checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

Comments
  • What is it: Partial? In my case it is interface IFilter {} type
  • @OPV explained Partial a bit.
  • Thank you, it is well!
  • I dont want to write set/get for each properties.
  • Something like this? new Filter({catagory: 5, subject: 4})