Junior — Middle
What is the difference between types and classes in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, classes are templates for creating objects with a specific structure and behavior (methods). They are compiled into JavaScript and used at runtime.
Types are constructs that exist only at compile time and are used to describe the shape of data, unions, intersections, etc. They do not affect the generated code.
Main differences:
- Classes can have method implementations, constructors, inheritance, encapsulation.
- Types describe data structures, can combine multiple types, create aliases.
- Classes exist at runtime, types only during compilation.
Example:
class User {
constructor(public name: string) {}
greet() {
console.log(`Hello, ${this.name}`);
}
}
type UserType = {
name: string;
age: number;
};
const user1 = new User('Alice');
user1.greet(); // Hello, Alice
const user2: UserType = { name: 'Bob', age: 30 };
Here, the User class creates objects with a greet method, while UserType simply describes the structure of an object.