Skip to content

Generics

ช่วยให้เราสามารถสร้าง reusable components ที่ทำงานกับหลายประเภทข้อมูลได้

Basic Usage

Generic Functions

ช่วยให้ฟังก์ชันสามารถทำงานกับหลาย type ได้ โดยไม่ต้องเขียนฟังก์ชันใหม่สำหรับแต่ละ type

ts
function 
identity
<
T
>(
arg
:
T
):
T
{
return
arg
;
} // การใช้งาน let
output
=
identity
<string>("hello");
let
output2
=
identity
<number>(42);

Generic Interfaces

ทำให้ interface สามารถรับ parameter type ได้ เหมาะสำหรับการสร้าง reusable interface

ts
interface 
GenericIdentityFn
<
T
> {
(
arg
:
T
):
T
;
}

Generic Classes

คลาสสามารถรับ type parameter ได้ ทำให้ property และ method ในคลาสใช้ type นั้นได้

ts
class 
GenericNumber
<
T
> {
zeroValue
:
T
;
add
: (
x
:
T
,
y
:
T
) =>
T
;
constructor(
zeroValue
:
T
,
add
: (
x
:
T
,
y
:
T
) =>
T
) {
this.
zeroValue
=
zeroValue
;
this.
add
=
add
;
} }

Advanced Topics

Constraints

ใช้สำหรับจำกัด type parameter ให้มี property หรือคุณสมบัติบางอย่าง

ts
function 
loggingIdentity
<
T
extends {
length
: number }>(
arg
:
T
):
T
{
console
.
log
(
arg
.
length
);
return
arg
;
}

Default Types

กำหนดค่า default ให้กับ type parameter เมื่อไม่ได้ระบุ type อย่างชัดเจน

ts
function 
createArray
<
T
= string>(
length
: number,
value
:
T
):
Array
<
T
> {
return
Array
(
length
).
fill
(
value
);
}