Indexed Access Types
Indexed access types trong TypeScript cung cấp cách để truy cập kiểu của property hoặc phần tử mảng.
tstypeA = {foo : number };typeFoo =A ["foo"];
tstypeA = {foo : number };typeFoo =A ["foo"];
Cú pháp Indexed Access Types
Indexed access types sử dụng bracket notation với kiểu.
tsObjectType["propertyName"];ArrayType[number];
tsObjectType["propertyName"];ArrayType[number];
Object Types và Indexed Access Types
Indexed access types cũng có thể sử dụng với union type.
tstypePerson = {name : string;age : number };typeT =Person ["name" | "age"];
tstypePerson = {name : string;age : number };typeT =Person ["name" | "age"];
Kết hợp với type operator keyof, bạn có thể lấy union type của tất cả các property trong object.
tstypeFoo = {a : number;b : string;c : boolean };typeT =Foo [keyofFoo ];
tstypeFoo = {a : number;b : string;c : boolean };typeT =Foo [keyofFoo ];
Nếu chỉ định tên property không tồn tại trong object type, compiler sẽ báo lỗi.
tstypeAccount = {name : string };typeProperty 'password' does not exist on type 'Account'.2339Property 'password' does not exist on type 'Account'.T =Account ["password" ];
tstypeAccount = {name : string };typeProperty 'password' does not exist on type 'Account'.2339Property 'password' does not exist on type 'Account'.T =Account ["password" ];
Array Types và Indexed Access Types
Indexed access types cũng có thể dùng để truy cập kiểu phần tử của array type. Để truy cập kiểu phần tử, thêm [number] vào array type.
tstypeStringArray = string[];typeT =StringArray [number];
tstypeStringArray = string[];typeT =StringArray [number];
Cũng hoạt động với array type có phần tử là union type.
tstypeMixedArray = (string | undefined)[];typeT =MixedArray [number];
tstypeMixedArray = (string | undefined)[];typeT =MixedArray [number];
Kết hợp với type operator typeof, bạn có thể trích xuất kiểu phần tử từ giá trị mảng.
tsconstarray = [null, "a", "b"];typeT = (typeofarray )[number];
tsconstarray = [null, "a", "b"];typeT = (typeofarray )[number];
Tuple Types và Indexed Access Types
Indexed access types cũng có thể dùng để truy cập kiểu phần tử của tuple type. Để truy cập kiểu phần tử của tuple, sử dụng numeric literal type trong bracket notation.
tstypeTuple = [string, number];typeT =Tuple [0];
tstypeTuple = [string, number];typeT =Tuple [0];
Kết hợp với type operator typeof, bạn có thể trích xuất kiểu phần tử từ giá trị tuple.
tsconststateList = ["open", "closed"] asconst ;typeState = (typeofstateList )[number];
tsconststateList = ["open", "closed"] asconst ;typeState = (typeofstateList )[number];
Chia sẻ kiến thức
Indexed access types của TypeScript có thể tham chiếu kiểu của property và phần tử mảng
・Cú pháp 1: ObjectType["propertyName"]
・Cú pháp 2: ArrayType[number]
・Kết hợp với keyof có thể lấy kiểu của tất cả property
・Kết hợp với typeof có thể lấy kiểu phần tử từ giá trị mảng
Từ 『Survival TypeScript』