Data Types Properties Functions and Events in TypeScript

What is a Data Type?

  1. Data type tells what kind of value a variable, property, function, or event will hold.
  2. Angular uses TypeScript, so data types are very important.


Data Type for Property (Class Property)

data: number | string | boolean | undefined;
  1. data is a property because it is defined inside the class.
  2. Multiple data types are allowed using | (pipe).
  3. This helps avoid assigning wrong values later.


Auto Type Detection

  1. TypeScript automatically detects type when value is assigned.
  2. 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));
}
  1. val → number
  2. user → string
  3. Function parameters must have defined data types.


Function Return Type

sum(a: number, b: number): number {
return a + b;
}
  1. Function returns a number
  2. Return type is defined after ) using : number


Calling Function with Parameters (HTML)

<button (click)="updateData(60,'anil sidhu')">Update Data</button>
  1. Passing a number and a string
  2. TypeScript checks types at compile time


Event Handling with Data Types

handleEvent(event: PointerEvent | Event | MouseEvent) {
console.log(event);
}
  1. One function handles multiple event types
  2. 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>
  1. click → PointerEvent
  2. change → Event
  3. mouseenter → MouseEvent


Property vs Variable

  1. Property → declared directly in class
  2. Variable → declared inside function using let or const


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?

  1. Prevents wrong value assignment
  2. Helps other developers understand code
  3. Errors are caught before runtime