Intro
Filtering requirements have grown. We need to be
able to filter any kind of Persons.
ํํฐ๋ง ์๊ตฌ์ฌํญ์ด ๋์์ต๋๋ค. ์ด์ Person์ ๋ชจ๋ ์ข ๋ฅ๋ฅผ ๊ตฌ๋ถํด์ผํฉ๋๋ค.
Exercise
Fix typing for the filterPersons so that it can filter users
and return User[] when personType='user' and return Admin[]
when personType='admin'. Also filterPersons should accept
partial User/Admin type according to the personType.
`criteria` argument should behave according to the
`personType` argument value. `type` field is not allowed in
the `criteria` field.
personType์ด user๋ผ๋ฉด User[]๋ฅผ, personType์ด admin์ด๋ฉด Admin[]๋ฅผ ๋ฆฌํดํ ์ ์๋๋ก filterPerson์ ํ์ ์ ๊ณ ์ณ๋ณด์ธ์. filterPerson์ personType์ ๋ฐ๋ผ User/Admin ํ์ ์ ์ผ๋ถ๋ฅผ ๋ฐ์์ผํฉ๋๋ค. criteria ์ธ์๋ personType ์ธ์์ ๊ฐ์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋๋ค. type ํ๋๋ criteria ํ๋์ ํ์ฉ๋์ง ์์ต๋๋ค.
Bonus
Implement a function `getObjectKeys()` which returns more
convenient result for any argument given, so that you don't
need to cast it.
let criteriaKeys = Object.keys(criteria) as (keyof User)[];
-->
let criteriaKeys = getObjectKeys(criteria);
์บ์คํ ํ ํ์ ์์ด ์ฃผ์ด์ง ์ธ์์ ๋ํ ๊ฒฐ๊ณผ๋ฅผ ๋ ํธํ๊ฒ ๋ฆฌํดํ๋ getObjectKeys() ํจ์๋ฅผ ๊ตฌํํด๋ณด์ธ์
Code
const getObjectKeys = <T>(criteria:T) => Object.keys(criteria) as (keyof T)[];
export function filterPersons(persons: Person[], personType: "user", criteria: Partial<User>): User[];
export function filterPersons(persons: Person[], personType: "admin", criteria: Partial<Admin>): Admin[];
export function filterPersons(persons: Person[], personType: string, criteria: Partial<Person>): Person[] {
return persons
.filter((person) => person.type === personType)
.filter((person) => {
let criteriaKeys = getObjectKeys(criteria);
return criteriaKeys.every((fieldName) => {
return person[fieldName] === criteria[fieldName];
});
});
}
๋ฌธ์ ์ ๋์จ๋๋ก Object.keys(criteria) ๋ถ๋ถ์ getObjectKeys๋ฅผ ์ด์ฉํ์ฌ ๋ฐ๋ก ๋นผ์ฃผ์๋ค.
criteria์ ํ์ ์ด ๋งค๋ฒ ๋ฌ๋ผ์ง๋ฏ๋ก ์ ๋ค๋ฆญ์ ์ด์ฉํ๋ค
filterPersons๊ฐ Userm Admin Person ๋ค์ํด์ ๋นํฉ์ค๋ฌ์ ๋๋ฐ ์ค๋ฒ๋ก๋ฉ์ผ๋ก ํด๊ฒฐํ๋ค.
๊ทธ๋ฅ ๋ ๋ค ์ ์๋ถํฐ ํด๋ ๋๋๊ฑฐ์๋ค.
From
https://typescript-exercises.github.io/#exercise=6&file=%2Findex.ts
'๐ Type Challenges > Typescript Exercises' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TS] TypeScript Exercises 7 ํด์ ๋ฐ ํ์ด (0) | 2023.07.19 |
---|---|
[TS] TypeScript Exercises 5 ํด์ ๋ฐ ํ์ด (0) | 2023.07.14 |
[TS] TypeScript Exercises 4 ํด์ ๋ฐ ํ์ด (0) | 2023.07.05 |
[TS] TypeScript Exercises 3 ํด์ ๋ฐ ํ์ด (0) | 2023.07.04 |
[TS] TypeScript Exercises 2 ํด์ ๋ฐ ํ์ด (0) | 2023.07.03 |