-
Book Overview & Buying
-
Table Of Contents
Mastering TypeScript - Fourth Edition
By :
A class is the definition of an object, what data it holds, and what operations it can perform. Classes and interfaces form the cornerstone of object-oriented programming. Let's take a look at a simple class definition, as follows:
class SimpleClass {
id: number;
print(): void {
console.log(`SimpleClass.print() called.`);
}
}
Here, we have defined a class, using the class keyword, which is named SimpleClass, and has an id property of type number, and a print function, which just logs a message to the console. Notice anything wrong with this code? Well, the compiler will generate an error message as follows:
error TS2564: Property 'id' has no initializer and is not definitely assigned in the constructor
What this error is indicating is that if we create an instance of this class, then the newly created class will not have the id property initialized, and it will therefore be undefined. If our code is expecting the id property...