Generics
μ¬μ¬μ© κ°λ₯ν μ»΄ν¬λνΈλ₯Ό ꡬμΆν μ μλ€. μ μ°ν κΈ°λ₯ λ¨μΌ νμ μ΄ μλ λ€μν νμ μ μ²λ¦¬ ν μ μλ μ»΄ν¬λνΈλ₯Ό λ§λ λ€.
function indentity(arg: any): any {
return arg;
}
anyλ₯Ό μ°λ κ²½μ° νμ μ€ν¬λ¦½νΈλ₯Ό μμ°κ² λ€λ λ»μ΄λ κ°λ€.
νμ λ³μ(type variable)
function idntity<T>(arg: T): T {
ruturn arg;
}
identity ν¨μλ λ€μν νμ μ μ²λ¦¬ν μ μλ€.
ν¨μνΈμΆ 2κ°μ§ λ°©λ²
let output = identity<string>("myString");
let output = identity("myString");
κΊ½μ κ΄νΈ(<>)μμ λͺ
μμ μΌλ‘ νμ
μ μ λ¬ν νμκ° μλ€. μΈμ myString
μ λ³΄κ³ Tλ₯Ό κ·Έ νμ
μΌλ‘ μ€μ νλ€.
Generic Type Variables
ν¨μκ° Tλμ μ Tλ°°μ΄μ μ²λ¦¬νλ€λ©΄
function loggingIdentity<T>(arg: T): T {
console.log(arg.length); // μ€λ₯: Tλ .length λ©μλλ₯Ό κ°μ§κ³ μμ§ μλ€.
return arg;
}
μ€λ₯ μμ΄ μμ±νκΈ°: 2κ°μ§ λ°©λ²
function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length); // μ€λ₯μμ Arrayλ .length λ©€λ²κ° μμ΅λλ€.
return arg;
}
function loggingIdenty<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}
Generic Types
νμ λ§€κ°λ³μκ° λ¨Όμ λμ΄λ λΉ μ λ€λ¦ ν¨μμ νμ
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: <T>(arg: T) => T = identity;
νμ λ³μμ μμ νμ λ³μμ μ¬μ©μ΄ μΌμΉνλ©΄ μ λ€λ¦ νμ λ§€κ°λ³μλ₯Ό λ€λ₯Έμ΄λ¦ μ¬μ© κ°λ₯
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: <U>(arg: U) => U = identity;
κ°μ²΄ 리ν°λ΄ λ°©μμ νΈμΆ νμ
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: {<T>(arg: T): T} = identity;
κ°μ²΄ 리ν°λ΄ λ°©μ + interface
interface GenericIdentityFn {
<T>(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn = identity;
μ λ€λ¦ μΈν°νμ΄μ€λ₯Ό λ§€κ°λ³μλ‘ μ΄λν μ μλ€.
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn<number> = identity;
Generic Classes
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y };
Generic Constraints
.length νλ‘νΌν°λ₯Ό κ°μ§ λͺ¨λ νμ μμ μλνλλ‘ μ νμ λκ³ μΆλ€. Tκ° λ¬΄μμ΄ λ μ μλμ§μ λν μ μ½μΌλ‘μ μꡬ μ¬νμ μμ±ν΄μΌ νλ€.
interface μ extends
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengtwise>(arg: T): T {
console.log(arg.length);
return arg;
}
Using Type Parameters in Generic Constraints
function getProperty<T, K extends keyof T>(obj: T, key:K) {
return obj[key];
}
let x = {a:1, b:2, c:3, d: 4};
getProperty(x, "a");
getProperty(x, "m"); // μ€λ₯: keyof Tμ ν΄λΉλμ§ μλλ€.
Using Class Types in Generics
μμ±μ ν¨μλ₯Ό μ¬μ©νμ¬ ν΄λμ€ νμ μ μ°Έμ‘°νλ€.
Last updated
Was this helpful?