Mảng TypeScript
TypeScript có một cú pháp cụ thể để gõ mảng.
Đọc thêm về mảng trong chương Mảng JavaScript của chúng tôi.
Ví dụ
const names: string[] = [];
names.push("Dylan"); // no error
// names.push(3); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Hãy tự mình thử »Chỉ đọc
Từ khóa chỉ readonly
có thể ngăn chặn việc thay đổi mảng.
Ví dụ
const names: readonly string[] = ["Dylan"];
names.push("Jack"); // Error: Property 'push' does not exist on type 'readonly string[]'.
// try removing the readonly modifier and see if it works?
Hãy tự mình thử »Kiểu suy luận
TypeScript có thể suy ra loại mảng nếu nó có giá trị.
Ví dụ
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error
// comment line below out to see the successful assignment
numbers.push("2"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
let head: number = numbers[0]; // no error
Hãy tự mình thử »