Performance: Interfaces for data models
This concept affects the build time and bundle size but does not impact runtime rendering or user experience directly.
export interface User { id: number; name: string; } // Used only at compile time for type checking
export class User { constructor(public id: number, public name: string) {} } // Used everywhere as a class instance
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using classes for data models | 0 | 0 | 0 | [!] OK - adds bundle size |
| Using interfaces for data models | 0 | 0 | 0 | [OK] Good - no runtime cost |
interface in Angular for data models?User with a string property name and a number property age?interface followed by the name and curly braces with property declarations.interface User { name: string; age: number; }. class User { name: string; age: number; } uses class, which is different. type User = { name: string; age: number; } uses type, which is valid but not an interface. function User(name: string, age: number) {} is a function, not an interface.console.log(user.age)?
interface User {
name: string;
age: number;
}
const user: User = { name: 'Anna', age: 30 };
console.log(user.age);User requires name as string and age as number. The object user matches this with name: 'Anna' and age: 30.user.age will output the number 30, as defined in the object.interface Product {
id: number;
name: string;
}
const product: Product = { id: 101, title: 'Book' };Product expects properties id and name. The object has id but uses title instead of name.title is not defined in Product and name is missing.Employee that has a required id (number), a required name (string), and an optional department (string). Which interface declaration is correct?? after the property name to indicate they may or may not be present.department as optional with department?: string;. interface Employee { id: number; name: string; department: string; } makes it required. interface Employee { id?: number; name?: string; department?: string; } makes all properties optional, which is incorrect. interface Employee { id: number; name: string; department: string | undefined; } uses string | undefined but does not mark it optional, which is less idiomatic.Pass the test and this pattern moves unknown