Literal Types
νμ μ§μ μ λμ± strictνκ² νΉμ κΈμλ μ«μλ§ κ°μ§ μ μκ² μ νμ λ μ μλ€.
// λ¬Έμμ΄ λ¦¬ν°λ΄ νμ
μ μ¬μ©ν νλΌλ―Έν°
function greet(name: "Alice" | "Bob"): "Hello, Alice!" | "Hello, Bob!" {
return `Hello, ${name}!`;
}
// μ«μ 리ν°λ΄ νμ
μ μ¬μ©ν νλΌλ―Έν°
function multiply(a: 2 | 3, b: 2 | 3): 6 {
return a * b;
}
// λΆλ¦¬μΈ 리ν°λ΄ νμ
μ μ¬μ©ν 리ν΄κ°
function isAdmin(userType: "admin" | "regular"): boolean {
return userType === "admin";
}
// μ¬μ© μμ
console.log(greet("Alice")); // Hello, Alice!
console.log(multiply(2, 3)); // 6
console.log(isAdmin("admin")); // true
λ¬Έμ μ
var data = {
name : 'kim'
}
function sayName(a : 'kim') {}
sayName(data.name)
μ μ½λλ μλ¬κ° λλ€. ν¨μλ 'kim' νμ λ§ μ λ ₯ν μ μλ€κ³ ν΄λ¨κ³ μλ£.name μ΄λΌλ건 string νμ μ΄μ§ 'kim' νμ μ΄ μλκΈ° λλ¬Έμ΄λ€.
ν΄κ²°νλ €λ©΄?
assertion μ¬μ©
var data = {
name: 'kim'
}
function sayName(a: 'kim') { }
sayName(data.name as 'kim'); // νμ
μ΄μ€μ
μ¬μ©
as const μ¬μ©
var data = {
name : 'kim'
} as const; // as const μ¬μ©
function sayName(a : 'kim') { }
sayName(data.name)
- νμ μ objectμ valueλ‘ λ°κΏμ€λ€. (νμ μ 'kim'μΌλ‘)
- objectμμ μλ λͺ¨λ μμ±μ readonlyλ‘ λ°κΏμ€λ€ (λ³κ²½νλ©΄ μλ¬λκ²)
objectλ₯Ό μ κ·Έκ³ μΆμΌλ©΄ as constλ₯Ό νμ©νμ.
μΆμ² : μ½λ©μ ν https://codingapple.com/ / TypeScript Documentation https://www.typescriptlang.org/docs/handbook/2/objects.html
'π TypeScript > κ°λ ' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[μ½λ©μ ν] νμ μ€ν¬λ¦½νΈ HTML μ‘°μμ μ£Όμμ (1) (0) | 2023.12.17 |
---|---|
[μ½λ©μ ν] ν¨μμ object λ©μλμ type alias μ§μ νκΈ° (0) | 2023.12.13 |
[μ½λ©μ ν] νμ μ λ³μμ λ΄μ : type alias (0) | 2023.12.11 |
νμ μ€ν¬λ¦½νΈ νμ μ μΆ(Type Inference) (0) | 2023.12.07 |
[μ½λ©μ ν] νμ μ€ν¬λ¦½νΈ νμ μ§μ λ°©λ² (0) | 2023.12.07 |