1. Classes in TypeScript Flashcards
What value do classes bring over having objects without classes?
It ensures consistency across the objects, as well as ensuring that certain objects will have certain properties.
How does a class relate to a prototype?
Classes are syntactic sugar around prototypes.
How do you assign a type to a property in TypeScript?
By using columns to specify its type.
eg. title : string;
How do you define a constructor for a class in TypeScript?
By using the constructor
keyword as if you were defining a method.
eg.
constructor(title:string, message:string) {
this.title = title;
this.message = message;
}
~~~
~~~
What are methods?
Functions that belong to our classes.
How do you define the return type of a method in TypeScript?
By using semicolons, after which you write the return type.
eg. doSomething() : string { //…
What is a getter in TypeScript?
A property that does some logic to return a value.
How do you define a getter in TypeScript?
By using the get
keyword and defining the rest like a function.
eg. get messageStatus() : string { //…
How do you call a getter of a class in TypeScript?
As if you were accessing one of its properties.
eg. message.messageStatus;
What is a setter in TypeScript?
A property that updates data while providing some additional logic.
How do you define a setter in TypeScript?
By using a setter and defining the rest like a function that takes in a value and assigns it to a private property.
eg.
private _isSent : boolean;
set isSent(value:boolean) {
this._isSent = value;
}
~~~
~~~
How do you use a setter in TypeScript?
By using an assignment operator to pass in the value it takes.
eg. message.isSent = true;