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

NoInfer

 NoInfer

Yosuke Kurami

December 22, 2023
Tweet

More Decks by Yosuke Kurami

Other Decks in Programming

Transcript

  1. ͜ͷܕఆٛ͋ͬͯΔʁ - ͓୊: ಉ͡ܕͷҾ਺ a ͱ b ͕Ұக͍ͯ͠Δ͔ݕࠪ͢Δؔ਺ - a

    ͱ b ͷܕ͕ҟͳΔ৔߹͸ίϯύΠϧΤϥʔͱ͍ͨ͠ declare function isEqual<T>(a: T, b: T): boolean; isEqual(100, 200); isEqual("hoge", "fuga"); // @ts-expect-error isEqual("hoge", 200);
  2. Τϥʔʹ͠ΖͬͭͬͯΜͩΖ 😇 - ͓୊: ಉ͡ܕͷҾ਺ a ͱ b ͕Ұக͍ͯ͠Δ͔ݕࠪ͢Δؔ਺ -

    a ͱ b ͷܕ͕ҟͳΔ৔߹͸ίϯύΠϧΤϥʔͱ͍ͨ͠ declare function isEqual<T>(a: T, b: T): boolean; isEqual( { id: "100", name: "hoge" }, { code: "200", name: "foo" }, );
  3. T ͕ਪ࿦͞Εա͍͗ͯΔ - isEqueal<T> ͷܕύϥϝʔλ T ͕ͲͷΑ͏ʹਪ࿦͞Ε͍ͯΔ͔ͱ͍͏ͱ: - ʮҾ਺ a,

    b ૒ํΛ୅ೖՄೳͳܕʯΛ Type Checker ͕ؤுͬͯਪ࿦ͯ͠ ͨ݁͠Ռɺ؇͍ܕʹͳͬͯ͠·͍ͬͯΔ - ʮҾ਺ b ͸ a ͱಉܕͰ͋Δ͜ͱʯ ΛදݱͰ͖͍ͯͳ͍ isEqual< | { id: string, name: string, code?: undefined } | { id?: undefined, name: string, code: string } >( { id: "100", name: "hoge" }, { code: "200", name: "foo" }, );
  4. ਪ࿦Λҙਤతʹఀࢭͤ͞Δ - TypeScript 5.4 Ͱ NoInfer ͱ͍͏૊ΈࠐΈܕͷ࣮૷͕ਐΜͰ͍Δ 
 ※ 2023.12.22

    Ͱ͸ not merged - https://github.com/microsoft/TypeScript/pull/56794 (օେ޷͖ Hejlsberg ޚେ) - NoInfer ͰϚʔΫ͞Εͨܕ͸ɺܕਪ࿦ͷ݁ՌʹӨڹ͠ͳ͍ 
 ্هྫͰ͸ɺҾ਺ b ͷܕ ͸ T ͦͷ΋ͷ ( i.e. Ҿ਺ a ͚ͩͰਪ࿦͞ΕΔ) declare function isEqual<T>(a: T, b: NoInfer<T>): boolean; isEqual( { id: "100", name: "hoge" }, { code: "200", name: "foo" }, );
  5. type NoInfer<T> = intrinsic; - NoInfer ͸ Intrinsic ͳܕ (͜ΕҎ্ଞͷܕͰදݱͰ͖ͳ͍ܕ)

    - Uppercase<T> ΍ Uncapitalize<T> ͳͲ TS 4.1 Ͱ஀ੜͨ͠ 4छͷΈ. 
 ࠓճͷ PR Ͱ͸ٱ͠ͿΓʹ5൪໨ͷ Intrinsic type ͕௥Ճ͞Ε͍ͯΔ - (༨ஊ) Uppercase ΍ Uncapitalize Λ௥Ճͨ͠ͷ΋ Hejlsberg ͳͷͰɺ Intrinsic Type ͸ޚେͷ੟Ҭͷ··
  6. NoInfer<T> ͷ࢓૊Έ - NoInfer<T> ͸ɺܕύϥϝʔλͰ͸ͳ͘ ܕ୅ೖ ( Type Substitution) ͱ͠

    ͯѻ͏Α͏ʹ࣮૷͞Ε͍ͯΔ - ܕ୅ೖ͸ʮʰ ଎΍͔ʹ T ͷܕΛల։ͯ͠Ͷʱͱ͍͏໋ྩʯͷΑ͏ͳ΋ͷ - طଘͷ TypeScript Ͱܕ୅ೖͱݟͳ͞ΕΔՕॴ͸ Conditional Type ͷΈ 
 ※ Type Substitution ࣗମɺ Conditional Type ͷͨΊʹ࣮૷͞Εͨ࢓૊Έ type Condition<T, S, U> = T extends S // ͜ͷ T ͸ܕύϥϝʔλ ? T // ͜ͷ T ͸ܕ୅ೖ : U
  7. - ܕ୅ೖ͸୅ೖର৅ͷܕ͕ຬ੍ͨ͢໿ͷܕΛอ͍࣋ͯ͠Δ - NoInfer<T> ͷ࣮ମ͸ɺ੍໿ʹ unknown Λ༩͑ͨ T ΁ͷ ܕ୅ೖ

    
 ͱɺ΄ͱΜͲͷจ຺Ͱಉ͡ҙຯ - unknown ͸ Top Type Ͱ͋ΔͨΊɺطଘͷ TS ʹ͸ ʮ unknown Λ੍໿ ͱͨ͠ܕ୅ೖʯ͸ଘࡏ͠ͳ͍ ʢ࡞Εͳ͍Α͏ʹͳ͍ͬͯͨ) 
 ͢ͳΘͪʮunknown Λ੍໿ͱͨ͠ܕ୅ೖ͸ NoInferͰ͋Δʯ͕੒ཱ͢Δ - ʮܕਪ࿦தʹ unknown Λ੍໿ͱͨ͠ܕ୅ೖ͕ग़ݱͨ͠Βɺਪ࿦Λఀࢭ ͢Δʯͱ͍͏ϩδοΫ͕௥Ճ͞Ε͍ͯΔ͚ͩ - NoInfer ͸ طଘͷ Type checker ͕࣋ͭ࢓૊Έ͚ͩͰ࣮ݱ͞Ε͍ͯΔ type NoInfer<T> = T type Condition<T, S, U> = T extends S ? T // ͜ͷ T ͸ܕ୅ೖ. ͨͩ͠ T ͸੍໿ S Λຬ͍ͨͯ͠Δ͜ͱ͕อূ͞Ε͍ͯΔ : U
  8. ͓ΘΓʹ - ਪ࿦ΛࢭΊ͍ͨ৔߹͸ NoInfer - ௨ৗͷΞϓϦέʔγϣϯίʔυͰ NoInfer ͕໾ʹཱͭ͜ͱ͸كͳ͸ͣ - ҙࣝ͢Δͷ͸ϥΠϒϥϦ࡞ऀ

    
 ࠓճͷ PR ΋ XState ίΞίϛολͷਓ͕ߟ͑ͨ෺͕ݪҊͱͳ͍ͬͯΔ 
 https://github.com/microsoft/TypeScript/pull/52968 - TS Type checker ʹͯ࠷খݶͷ࿑ྗͰਪ࿦ΛࢭΊΔ࢓૊Έ͕໘ന͍