Menu
CoddyTech

Classes and Methods

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 1 of 24.

A class describes objects with fields and methods. A field holds a value; a method is a function belonging to the object. Creating an instance with new gives you an object built from that class.

class Card {
    title: string = 'Welcome';
    label() { return this.title; }
}
const card = new Card();
card.label(); // 'Welcome'

The type annotation string tells the editor that title holds text. Inside label, this refers to the instance whose method was called. Two instances can hold different titles. The ready server uses your class and displays the method results; its Nest setup will be introduced next.

challenge icon

Challenge

Easy

Edit src/exercise.ts. Add a label() method to TaskCard. Return this instance’s title prefixed with [done] when its done field is true, or [todo] otherwise. Include the space after the bracket.

Try it: GET /result shows ["[done] Read","[todo] Write"]. The supplied controller creates two instances and assigns their fields. Before your method exists, it shows No label method.

Try it yourself

export class TaskCard {
    title: string = '';
    done: boolean = false;
    // Add a label method that uses this instance's fields.
}

All lessons in TypeScript and NestJS

Practice on your own: Express playground