Variables, Data Types, and Interfaces in Angular (TypeScript)

Variables, Data Types, and Interfaces in Angular (TypeScript)

Variables, Data Types, and Interfaces in Angular (TypeScript)

These are foundational concepts that make your Angular app type-safe, scalable, and easier to maintain.


🔹 1. Variables in TypeScript

TypeScript is strongly typed, so you can (and should) define the type of your variables.

✅ Syntax:

let name: string = "Angular";
const version: number = 17;
var isAwesome: boolean = true;

🔄 `let` vs `const` vs `var`:

Keyword Scope Reassignable Hoisted
`let` Block ✅ Yes ❌ No
`const` Block ❌ No ❌ No
`var` Function ✅ Yes ✅ Yes

🔹 2. Data Types in TypeScript

Type Example
`string` `"Angular"`
`number` `42`
`boolean` `true`, `false`
`any` Anything (use with caution)
`array` `string[]`, `number[]`
`tuple` `[string, number]`
`enum` `enum Status { Active, Inactive }`
`object` `{ name: string, age: number }`
`null` & `undefined` `null`, `undefined`
`union` `string | number`

Example:

let names: string[] = ["John", "Jane"];
let user: [string, number] = ["Alice", 30];

🔹 3. Interfaces

Interfaces define the shape of objects. They're especially useful in Angular for defining models, HTTP responses, etc.

✅ Defining an Interface

interface User {
  id: number;
  name: string;
  email?: string; // Optional property
}

🛠 Using Interfaces

const user: User = {
  id: 1,
  name: "Alice"
};

👍 Interface with Functions

interface Greeter {
  greet(name: string): string;
}

class MyGreeter implements Greeter {
  greet(name: string): string {
    return `Hello, ${name}`;
  }
}

🧠 Summary

  • Use `let`, `const`, and define types for type safety.
  • Leverage TypeScript’s strong typing to catch errors early.
  • Use interfaces to describe complex object shapes clearly and enforce consistency.

Comments

Popular posts from this blog

Car Wash System vb.net

Face recognition using EmguCV 3.0 and typing pattern recognition

Student Information System - AngularJS , ASP.NET API, C#