TYPESCRIPT
TypeScript Property: Syntax, Usage, and Examples
A TypeScript property refers to a named value inside an object, class, or interface. Properties define the structure of objects and control how data is stored and accessed. TypeScript adds type safety to properties, ensuring they hold the correct type of value.
How to Use Properties in TypeScript
Defining Properties in Objects
You can define properties directly in an object. TypeScript will infer the types automatically, or you can explicitly define them.
const user: { name: string; age: number } = {
name: "Alice",
age: 30,
};
console.log(user.name); // Output: Alice
Adding Properties to Objects
To add a property to an object in TypeScript, use type assertion or index signatures to extend the object dynamically.
const user = { name: "Alice" } as { name: string; age?: number };
user.age = 30;
console.log(user.age); // Output: 30
Using index signatures, you can allow objects to have additional dynamic properties.
type User = { name: string; [key: string]: any };
const user: User = { name: "Alice", age: 30, city: "New York" };
console.log(user.city); // Output: New York
Defining Properties in Classes
A TypeScript class property is defined inside a class and can have different access modifiers (public
, private
, protected
).
class Person {
public name: string;
private age: number; // Only accessible inside the class
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const person = new Person("Bob", 25);
console.log(person.name); // Output: Bob
// console.log(person.age); // Error: Property 'age' is private
Optional Properties
A TypeScript optional property is defined using the ?
symbol, meaning it may or may not be present in the object.
type Car = {
brand: string;
model: string;
year?: number; // Optional property
};
const car1: Car = { brand: "Toyota", model: "Corolla" };
const car2: Car = { brand: "Honda", model: "Civic", year: 2022 };
console.log(car1.year); // Output: undefined
console.log(car2.year); // Output: 2022
Read-Only Properties
To prevent modification of a property after initialization, use readonly
.
class Book {
readonly title: string;
constructor(title: string) {
this.title = title;
}
}
const myBook = new Book("TypeScript Basics");
// myBook.title = "Advanced TypeScript"; // Error: Cannot assign to 'title' because it is a read-only property
When to Use Properties in TypeScript
Structuring Objects
Use properties to define the structure of objects and maintain consistency in your data.
type User = { id: number; username: string };
const user: User = { id: 1, username: "coder123" };
Managing Class Instances
Class properties store instance-specific data and control access through encapsulation.
class Employee {
constructor(public id: number, public name: string) {}
}
const employee = new Employee(101, "Alice");
console.log(employee.id); // Output: 101
Adding Dynamic Properties
Use index signatures to allow objects to have additional properties without a fixed structure.
type Config = { [key: string]: string };
const settings: Config = { theme: "dark", language: "en" };
console.log(settings.language); // Output: en
Examples of Using Properties in TypeScript
Checking If a Property Exists
To check if a property exists, use the in
operator.
const user = { name: "Alice", age: 30 };
console.log("age" in user); // Output: true
console.log("city" in user); // Output: false
Alternatively, use optional chaining (?.
) to avoid runtime errors.
console.log(user.city?.toUpperCase()); // Output: undefined (no error)
Handling Missing Properties
If you try to access a property that is not defined in the type, TypeScript throws an error.
type User = { name: string };
const user: User = { name: "Alice" };
// console.log(user.age); // Error: Property 'age' does not exist on type 'User'
Use index signatures if you need dynamic properties.
type UserDynamic = { name: string; [key: string]: any };
const userDynamic: UserDynamic = { name: "Alice", age: 30 };
console.log(userDynamic.age); // Output: 30
Removing a Property from an Object
To remove a property from an object, use the delete
keyword.
const user = { name: "Alice", age: 30 };
delete user.age;
console.log(user); // Output: { name: "Alice" }
Sorting an Array of Objects by a Property
Sorting an array of objects by a property is common in TypeScript. Use sort()
.
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 },
];
users.sort((a, b) => a.age - b.age);
console.log(users); // Output: Sorted by age
Extending Interfaces and Adding Properties
You can extend an interface to add a property using extends
.
interface User {
name: string;
}
interface Admin extends User {
role: string;
}
const admin: Admin = { name: "Alice", role: "SuperAdmin" };
console.log(admin.role); // Output: SuperAdmin
Adding a Property to a Type
To add a property to a type, use &
(intersection type).
type User = { name: string };
type Admin = User & { role: string };
const admin: Admin = { name: "Alice", role: "Admin" };
Learn More About TypeScript Properties
Getters and Setters
Use getters and setters to control how a property is accessed and modified.
class Person {
private _age: number = 0;
get age() {
return this._age;
}
set age(value: number) {
if (value < 0) throw new Error("Age must be positive.");
this._age = value;
}
}
const person = new Person();
person.age = 25;
console.log(person.age); // Output: 25
Static Properties
Static properties belong to a class rather than an instance.
class App {
static version = "1.0.0";
}
console.log(App.version); // Output: 1.0.0
Computed Properties
Computed properties dynamically generate property names.
const key = "status";
const obj = { [key]: "active" };
console.log(obj.status); // Output: active
TypeScript properties define object structures, ensuring type safety and flexibility. You can declare properties in objects, classes, and interfaces, making them fundamental in TypeScript development.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.