type Combinable = number | string; type ConversionDescriptor = 'as-number' | 'as-text';
type aliasesλ μΌλ°μ μΌλ‘ unionμΌλ‘ μ¬μ©λλ€.
function combine( input1: Combinable, input2: Combinable, resultConversion: ConversionDescriptor ) { let result; if (typeof input1 === 'number' && typeof input2 === 'number' || resultConversion === 'as-number') { result = +input1 + +input2; } else { result = input1.toString() + input2.toString(); } return result; // if (resultConversion === 'as-number') { // return +result; // } else { // return result.toString(); // } }
νμ λ³μΉ(Type Alias)
νμ
λ³μΉ(type alias)μ μ΄μ©ν΄ μ΄λ―Έ μ‘΄μ¬νλ νμ
μ λ€λ₯Έ μ΄λ¦μ λΆμ¬ 볡μ‘ν νμ
μ κ°λ¨νκ² μΈ μ μλ€. λν, νλ‘κ·Έλλ¨Έμ μλλ₯Ό λ³΄λ€ λͺ
ννκ² λνλΌ μ μλ€.
νμ λ³μΉ μ μ
// type NewType = Type; type UUID = string; type Height = number; type AnotherUUID = UUID; type Animals = Animal[]; type User = { name: string; height: number; };
μ΄ λ λ³μΉμ λ¨μν μλ‘μ΄ μ΄λ¦μ λΆμΌ λΏμ΄κ³ , μ€μ λ‘ μλ‘μ΄ νμ
μ΄ μμ±λλ κ²μ μλλΌλ μ μ μ μνλΌ. μλ₯Ό λ€μ΄, μλμ κ°μ μ½λμ μλ¬ λ©μμ§μλ UUID λμ string μ΄ μ¬μ©λλ€.
type UUID = string; function getUser(uuid: UUID) { /* ν¨μ λ³Έλ¬Έ */ } getUser(7); // error TS2345: Argument of type '7' is not assignable to parameter of type 'string'.
Β