Data Types Properties Functions and Events in TypeScript
What is a Data Type?
- Data type tells what kind of value a variable, property, function, or event will hold.
- Angular uses TypeScript, so data types are very important.
Data Type for Property (Class Property)
data: number | string | boolean | undefined;
datais a property because it is defined inside the class.- Multiple data types are allowed using
|(pipe). - This helps avoid assigning wrong values later.
Auto Type Detection
- TypeScript automatically detects type when value is assigned.
- But manual type definition is needed when multiple data types are possible.
Function with Parameter Data Types
updateData(val: number, user: string) {
this.data = val;
console.log(user);
console.log(this.sum(10, 20));
}
val→ numberuser→ string- Function parameters must have defined data types.
Function Return Type
sum(a: number, b: number): number {
return a + b;
}
- Function returns a number
- Return type is defined after
)using: number
Calling Function with Parameters (HTML)
<button (click)="updateData(60,'anil sidhu')">Update Data</button>
- Passing a number and a string
- TypeScript checks types at compile time
Event Handling with Data Types
handleEvent(event: PointerEvent | Event | MouseEvent) {
console.log(event);
}
- One function handles multiple event types
- Uses
|to support multiple events
Event Binding Examples (HTML)
<button (click)="handleEvent($event)">Click</button>
<input type="text" (change)="handleEvent($event)">
<div (mouseenter)="handleEvent($event)">
<h1>Test event</h1>
</div>
click→ PointerEventchange→ Eventmouseenter→ MouseEvent
Property vs Variable
- Property → declared directly in class
- Variable → declared inside function using
letorconst
Complete Example Code (Used in Video)
<h1>Data Type</h1>
<h2>{{data}}</h2>
<button (click)="updateData(60,'anil sidhu')">Update Data</button>
<button (click)="handleEvent($event)">Click</button>
<input type="text" (change)="handleEvent($event)">
<div (mouseenter)="handleEvent($event)">
<h1>Test event</h1>
</div>
data: number | string | boolean | undefined;
updateData(val: number, user: string) {
this.data = val;
console.log(user);
console.log(this.sum(10, 20));
}
sum(a: number, b: number): number {
return a + b;
}
handleEvent(event: PointerEvent | Event | MouseEvent) {
console.log(event);
}
Why Data Types Are Important?
- Prevents wrong value assignment
- Helps other developers understand code
- Errors are caught before runtime