๐Ÿ’™ Type Challenges/Typescript Exercises

[TS] TypeScript Exercises 4 ํ•ด์„ ๋ฐ ํ’€์ด

์„ ๋‹ฌ 2023. 7. 5. 15:23
๋ฐ˜์‘ํ˜•

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 Exercises

A set of interactive TypeScript exercises

typescript-exercises.github.io

 

๋ฐ˜์‘ํ˜•