Generics ขั้นพื้นฐาน
// JavaScript
function getFirst(arr) {
return arr[0]
}
getFirst([1, 2, 3]) // 1
getFirst(["One", "Two", "Three", "Four", "Five"]) // "One"// TypeScript
function getFirst(arr: number[]): number {
return arr[0]
}
getFirst([1, 2, 3]) // 1
getFirst(["One", "Two", "Three", "Four", "Five"]) // Type Errorfunction getFirst(arr: any[]): any {
return arr[0]
}
const a = getFirst([1, 2, 3]) // a: any
const b = getFirst(["One", "Two", "Three", "Four", "Five"]) // b: anyLast updated