[ν•œμž…] πŸ“’Day14 Quiz

TKΒ·2023λ…„ 12μ›” 22일
0

[κ°•μ˜] ν•œμž… μ‹œλ¦¬μ¦ˆ

λͺ©λ‘ 보기
56/59
post-custom-banner

Quiz 1.

/*
[ 문제 μ†Œκ°œ ]
λ‹€μŒ μš”κ΅¬μ‚¬ν•­μ„ λ§Œμ‘±ν•˜λŠ” IsProductKey<T> νƒ€μž…μ„ μ™„μ„±ν•˜μ„Έμš”
- IsProductKey νƒ€μž…μ€ 쑰건뢀 νƒ€μž…μœΌλ‘œ λ‹€μŒ 쑰건에 따라 각각 λ‹€λ₯Έ νƒ€μž…μœΌλ‘œ κ²°μ •λ©λ‹ˆλ‹€.
  - Tκ°€ Product의 key(ν”„λ‘œνΌν‹° 이름)쀑 ν•˜λ‚˜μΌ 경우 κ²°κ³ΌλŠ” true νƒ€μž…μ΄ λ©λ‹ˆλ‹€.
  - Tκ°€ Product의 key(ν”„λ‘œνΌν‹° 이름)쀑 ν•˜λ‚˜κ°€ 아닐 경우 κ²°κ³ΌλŠ” false νƒ€μž…μ΄ λ©λ‹ˆλ‹€.
  - 예λ₯Ό λ“€λ©΄ λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.
    - ex) IsProductKey<"id"> νƒ€μž…μ€ true νƒ€μž…μ΄ λ©λ‹ˆλ‹€.
    - ex) IsProductKey<"author"> νƒ€μž…μ€ false νƒ€μž…μ΄ λ©λ‹ˆλ‹€.
*/

/* [Quiz] μ•„λž˜μ˜ μ½”λ“œλ₯Ό μˆ˜μ •ν•˜μ„Έμš” */
interface Product {
  id: number;
  name: string;
  price: number;
  seller: {
    id: number;
    name: string;
    company: string;
  };
}

type IsProductKey<T> = any;

/* [Test] μ—¬κΈ°λΆ€ν„°λŠ” 정닡을 μ²΄ν¬ν•˜κΈ° μœ„ν•œ μš©λ„λ‘œ μˆ˜μ •ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€ */
import { Equal, Expect } from "@type-challenges/utils";

type TestCases = [
  Expect<Equal<IsProductKey<"id">, true>>,
  Expect<Equal<IsProductKey<"name">, true>>,
  Expect<Equal<IsProductKey<"author">, false>>,
  Expect<Equal<IsProductKey<"winterlood">, false>>
];

βœοΈλ‹΅μ•ˆ

type IsProductKey<T> = T extends keyof Product ? true : false;

μ½”λ“œλ§ν¬

Quiz 2.

/*
[ 문제 μ†Œκ°œ ]
λ‹€μŒ 쑰건을 λ§Œμ‘±ν•˜λŠ” Extract<T, U> νƒ€μž…μ„ κ΅¬ν˜„ν•˜μ„Έμš”
- Extract<T, U> νƒ€μž…μ€ Tλ‘œλΆ€ν„° U만 μΆ”μΆœν•˜λŠ” νƒ€μž…μž…λ‹ˆλ‹€.
  - ex) Extract<string | boolean, boolean>은 boolean νƒ€μž…μ΄ λ©λ‹ˆλ‹€.
  - ex) Extract<number | string, string>은 string νƒ€μž…μ΄ λ©λ‹ˆλ‹€.

(νžŒνŠΈπŸ’‘ κ°•μ˜ 쀑 직접 κ΅¬ν˜„ν•˜λŠ” Exclude νƒ€μž…μ˜ λ°˜λŒ€λΌκ³  μƒκ°ν•΄λ³΄μ„Έμš”!)
*/

/* [Quiz] μ•„λž˜μ˜ μ½”λ“œλ₯Ό μˆ˜μ •ν•˜μ„Έμš” */
type Extract<T, U> = any;

/* [Test] μ—¬κΈ°λΆ€ν„°λŠ” 정닡을 μ²΄ν¬ν•˜κΈ° μœ„ν•œ μš©λ„λ‘œ μˆ˜μ •ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€ */
import { Equal, Expect } from "@type-challenges/utils";

type TestCases = [
  Expect<Equal<Extract<string | number, string>, string>>,
  Expect<Equal<Extract<string | number, number>, number>>
];

βœοΈλ‹΅μ•ˆ

type Extract<T, U> = T extends U? never : U;

μ½”λ“œλ§ν¬


Quiz 3.

/*
[ 문제 μ†Œκ°œ ]
λ°°μ—΄ νƒ€μž…μ˜ μš”μ†Œλ₯Ό μΆ”μΆœν•˜λŠ” InferArrayType<T> νƒ€μž…μ„ κ΅¬ν˜„ν•˜μ„Έμš”
*/

/* [Quiz] μ•„λž˜μ˜ μ½”λ“œλ₯Ό μˆ˜μ •ν•˜μ„Έμš” */
type InferArrayType<T> = any;

/* [Test] μ—¬κΈ°λΆ€ν„°λŠ” 정닡을 μ²΄ν¬ν•˜κΈ° μœ„ν•œ μš©λ„λ‘œ μˆ˜μ •ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€ */
import { Expect, Equal } from "@type-challenges/utils";

const arr1 = [1, 2, 3];
const arr2 = ["hello", "myname", "winterlood"];
const arr3 = [1, true, "hi"];

type TestCases = [
  Expect<Equal<InferArrayType<typeof arr1>, number>>,
  Expect<Equal<InferArrayType<typeof arr2>, string>>,
  Expect<Equal<InferArrayType<typeof arr3>, number | string | boolean>>
];

βœοΈλ‹΅μ•ˆ

type InferArrayType<T> = T extends (infer R)[]? R :never;

μ½”λ“œλ§ν¬

profile
μ‰¬μš΄κ²Œ 쒋은 FE개발자😺
post-custom-banner

0개의 λŒ“κΈ€