Intro
As we introduced "type" to both User and Admin
it's now easier to distinguish between them.
Once object type checking logic was extracted
into separate functions isUser and isAdmin -
logPerson function got new type errors.
μ μ μ μ΄λλ―Όμ λν΄ typeμ μκ°νλ―μ΄, μ΄μ μ΄ λμ ꡬλΆνλ건 μ¬μμ‘μ΅λλ€. λ‘μ§μ κ²μ¬νλ κ°μ²΄ νμ μ μΆμΆν΄μ isUserκ³Ό isAdmin ν¨μμ λΆλ¦¬ν΄μ λ£μλλ logPerson ν¨μμ μλ‘μ΄ νμ μλ¬κ° μκ²Όμ΅λλ€
Exercise
Figure out how to help TypeScript understand types in
this situation and apply necessary fixes.
μ΄ μν©μμ νμ μ€ν¬λ¦½νΈκ° νμ μ μ΄ν΄ν μ μκ² λμμ€ μ μμμ§ μμλ΄κ³ μμ ν΄μ£ΌμΈμ
Code
νΉμ λ³μκ° νΉμ νμ μΈμ§ μλμ§λ₯Ό λ°ννλ person is Admin ννλ₯Ό μ¬μ©νλ€.
booleanκ³Ό λΉμ·νλ©΄μλ λ€λ₯΄λ€
export function isAdmin(person: Person): person is Admin {
return person.type === 'admin';
}
export function isUser(person: Person): person is User{
return person.type === 'user';
}
From
https://typescript-exercises.github.io/#exercise=4&file=%2Findex.ts
'π Typescript > Typescript Exercises' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[TS] TypeScript Exercises 5 ν΄μ λ° νμ΄ (0) | 2023.07.17 |
---|---|
[TS] TypeScript Exercises 5 ν΄μ λ° νμ΄ (0) | 2023.07.14 |
[TS] TypeScript Exercises 3 ν΄μ λ° νμ΄ (0) | 2023.07.04 |
[TS] TypeScript Exercises 2 ν΄μ λ° νμ΄ (0) | 2023.07.03 |
[TS] TypeScript Exercises 1 ν΄μ λ° νμ΄ (0) | 2023.07.03 |