Saturday, February 15, 2025
HomeLập Trình TypeScriptobject Type | Lập trình TypeScript

object Type | Lập trình TypeScript

1. Giới thiệu về object

Kiểu object là một kiểu được xây dựng sẵn trong TypeScript, nó là kiểu non-primitives. Nhắc lại về các kiểu primitives bao gồm: number, bigint, string, boolean, null, undefined, symbol. Các kiểu non-primitive phổ biến là object, arrays, functions và các object khác.

Ví dụ:

TypeScript
let car: object; // khai báo biến car kiểu object

// khai báo và khởi tạo biến car kiểu object
let cat: object = {
  name: "Kitty",
  age: 2,
  type: "Ragdoll",
};

// Khai báo biến arrayObject kiểu object với giá trị là mảng
let arrayObject: object = ["Orange", 25, "Apple", 66, 52];

// Khai báo biến functionObject kiểu object với giá trị là function
let functionObject: object = function () { 
  return "Hello";
};

1.1. object chỉ chấp nhận non-premitive

Các trường hợp sau sẽ dấn đế sai, không thể gán kiểu object cho các kiểu primitive. Ví dụ một số trường hợp

TypeScript
// Khai báo sai 
let numberObject: object = 15; // Error
let undefinedObject: object = undefined; // Error
let nullObject: object = null; // Error

1.2 Xác định kiểu dữ liệu cho thuộc tính

Bạn có thể xác định cụ thể kiểu của thuộc tính trong object để thực hiện type-safe

TypeScript
// Khai báo biến employee với các thuộc tính xác định kiểu dữ liệu
let employee: {
  readonly id: number;
  firstName: string;
  lastName: string;
  dateOfBirth: string;
};

// Khởi tạo giá trị hợp lệ
employee = {
  id: 0,
  firstName: "Nguyen",
  lastName: "Minh Chau",
  dateOfBirth: "11/03/97",
};

// Nếu thay đổi giá trị khác kiểu dữ liệu quy ước sẽ xảy ra lỗi
employee.id = 123; // Error: Cannot assign to 'id' because it is a read-only property
employee.id = "123"; // Error: Cannot assign a string to a number property
employee.firstName = 123; // Error: Cannot assign a number to a string property

1.3. Gộp cú pháp vừa khai báo vừa khởi tạo

TypeScript
let employee: {
  readonly id: number;
  firstName: string;
  lastName: string;
  dateOfBirth: string;
} = {
  id: 0,
  firstName: "Nguyen",
  lastName: "Minh Chau",
  dateOfBirth: "11/03/97",
};

1.4. Sử dụng cú pháp Type Assertion

Cú pháp này dùng để xác nhận kiểu dữ liệu của đối tượng bằng từ khóa as để góp phần đảm bảo type-safe.

TypeScript
let apple: object = { name: "Apple", price: 10000, color: "Red" };
console.log(
  `Price: ` + (apple as { name: string; price: number; color: string }).price // 10000
);

2. Sử dụng Interface để khai báo một đối tượng

Thay vì sử dụng từ khóa object thì một cách thay thế tốt hơn đó là dùng interface

TypeScript
interface IEmployee {  
  id: number;
  firstName: string;
  lastName: string;
  dateOfBirth: string;
} 
let person: IEmployee = {
  id: 0,
  firstName: "Jikey",
  lastName: "Milano",
  dateOfBirth: "11/03/24",
};  

3. Phân biệt object với Object

objectkiểu dữ liệu non-primitive và không có các phương thức từ Object.prototype. phù hợp với type-safe.
Objectkiểu contructor với các method hỗ trợ như toString(),hasOwnProperty(),… không phù hợp với type-safe vì có thể nhận các giá trị null, undefined.

Ví dụ về kiểu Object

TypeScript
let jikey: Object = { name: "Jikey", age: 24, address: "Hanoi" };
console.log(jikey.hasOwnProperty("name")); // true
console.log(jikey.valueOf()); // { name: 'Jikey', age: 24, address: 'Hanoi' }

4. Sử dụng Record<string,any> để tạo một object linh hoạt

TypeScript
let obj: Record<string, any> = { name: "John", age: 30, "home address": "123 Main St" };

// Truy cập thuộc tính "name" bằng cách sử dụng dấu ngoặc vuông
console.log(obj["name"]);  // Output: John

// Truy cập thuộc tính "home address"
console.log(obj["home address"]);  // Output: 123 Main St

// Sử dụng biến làm key
let key = "age";
console.log(obj[key]);  // Output: 30

Nguyễn Minh Châu
Nguyễn Minh Châuhttps://nhatkydev.com
Hi guys ! I'm a software developer. I love programming and new technologies. I create non-professional content on this website, you can only view it for reference purposes.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular