๐Ÿ’™ Type Challenges/Typescript Exercises

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

์„ ๋‹ฌ 2023. 7. 14. 21:01
๋ฐ˜์‘ํ˜•

Intro

    Time to filter the data! In order to be flexible
    we filter users using a number of criteria and
    return only those matching all of the criteria.
    We don't need Admins yet, we only filter Users.

 

๋ฐ์ดํ„ฐ๋ฅผ ์„ ๋ณ„ํ•  ์ฐจ๋ก€์ž…๋‹ˆ๋‹ค! ๋ณด๋‹ค ์œ ์—ฐํ•ด์ง€๊ธฐ ์œ„ํ•ด ์šฐ๋ฆฌ๋Š” ๊ธฐ์ค€์„ ํ‘œ์‹œํ•˜๋Š” ์ˆซ์ž๋ฅผ ์ด์šฉํ•˜์—ฌ ์œ ์ €๋“ค์„ ํ•„ํ„ฐ๋งํ•˜๊ณ , ์˜ค์ง ์ด ๋ชจ๋“  ๊ธฐ์ค€์— ๋งž๋Š” ์œ ์ €๋“ค๋งŒ ๋ฆฌํ„ดํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. ์•„์ง Admin๋“ค์€ ํ•„์š”ํ•˜์ง€ ์•Š๊ณ  User๋“ค๋งŒ ํ•„ํ„ฐ๋งํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

Exercise

    Without duplicating type structures, modify
    filterUsers function definition so that we can
    pass only those criteria which are needed,
    and not the whole User information as it is
    required now according to typing.

 

ํƒ€์ž…๊ตฌ์กฐ๋ฅผ ๋ณต์ œํ•˜์ง€ ๋ง๊ณ , filterUsers ํ•จ์ˆ˜์˜ ์ •์˜๋ถ€๋ถ„์„ ์ˆ˜์ •ํ•ด์„œ ์ „์ฒด ์œ ์ € ์ •๋ณด๊ฐ€ ์•„๋‹Œ ํ•„์š”ํ•œ ๊ธฐ์ค€๋งŒ ํ†ต๊ณผ์‹œ์ผœ์ฃผ์„ธ์š”.

 

    Exclude "type" from filter criteria.

๋ณด๋„ˆ์Šค ๋ฌธ์ œ : ํ•„ํ„ฐ ๊ธฐ์ค€์—์„œ "type"์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ˆ˜ํ–‰ํ•ด๋ณด์„ธ์š”

 

Code

export function filterUsers(persons: Person[], criteria: Partial<User>): User[] {
    return persons.filter(isUser).filter((user) => {
        const criteriaKeys = Object.keys(criteria) as (keyof User)[];
        return criteriaKeys.every((fieldName) => {
            return user[fieldName] === criteria[fieldName];
        });
    });
}

 

์ฒ˜์Œ์—๋Š” Object extends User๋กœ ํ–ˆ๋Š”๋ฐ ๋ฌผ์Œํ‘œ๊ฐ€ ๋น ์กŒ๋‹ค๋Š” ๊ฒฝ๊ณ ๊ฐ€ ๋– ์„œ ์‹คํŒจํ–ˆ๋‹ค ใ… ใ… 

 

From

https://typescript-exercises.github.io/#exercise=5&file=%2Findex.ts

 

TypeScript Exercises

A set of interactive TypeScript exercises

typescript-exercises.github.io

 

๋ฐ˜์‘ํ˜•