Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScriptのextends

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 TypeScriptのextends

Avatar for MisakiSoeda

MisakiSoeda

April 23, 2025
Tweet

Other Decks in Programming

Transcript

  1. FYUFOETͷجຊ T extends U ? X : Y w FYUFOET͸ʮܕ͕৚݅Λຬ͍ͨͯ͠Δ͔ʁʯΛ൑அ͢Δ৚݅ܕͷΩʔߏจɻ

    w ଞͷUZQFPG΍JO͕࣮ߦ࣌ͷ஋ʹج͍ͮͯܕΛߜΓࠐΉͷʹର͠ɺ 
 FYUFOETΛ࢖ͬͨ৚݅ܕ͸ 
 ʮܕͦͷ΋ͷ͚ͩΛݟͯॲཧΛ෼͚Δʯ७ਮͳܕϨϕϧͷ෼ذͰ͢ɻ
  2. ྫ6OJPOܕͷϑΟϧλϦϯά ໨త6OJPO͔Βಛఆͷܕ͚ͩநग़ type OnlyStrings<T> = T extends string ? T

    : never; type Mixed = "hello" | 42 | "world"; type JustStrings = OnlyStrings<Mixed>; // "hello" | "world" 6OJPOܕʹରͯ͠5FYUFOETʜͱॻ͘ͱɺ֤ߏ੒ཁૉʹରͯ͠ݸผʹධՁ͞ ΕΔl෼഑zͱ͍͏࢓༷͕͋Γ·͢ɻ
  3. ྫΦϒδΣΫτͷܕΛಛఆ͢Δ ໨తಛఆͷϓϩύςΟΛ࣋ͭܕ͚ͩΛநग़ type Event = | { type: "click"; x:

    number } | { type: "scroll"; y: number }; type ExtractByType<T, K extends string> = T extends { type: K } ? T : never; type ClickEvent = ExtractByType<Event, "click">; // => { type: "click"; x: number }
  4. ྫFYUFOETͷ࢖͍ํʢ੍໿ˍ৚݅ܕʣ // ੍໿ͱͯ͠ͷextends function logLength<T extends { length: number }>(value:

    T) { console.log(value.length); } // ৚݅ܕͱͯ͠ͷextends type OnlyStrings<T> = T extends string ? T : never;