https://youtu.be/g9FL8hKoNqE?si=tsCYUjwOX5Z0AqZk

๋ถ„์„

Typescript ์˜ต์…˜์œผ๋กœ ์„ฑ๋Šฅ ๋ฌธ์ œ ์ง„๋‹จ

  • extendedDiagnostics ๋กœ ๋Œ€๋žต์ ์ธ ์ปดํŒŒ์ผ ์‹œ๊ฐ„ ํ™•์ธ ๊ฐ€๋Šฅ
  • generateTrace ๋กœ ํŠธ๋ ˆ์ด์Šค ํŒŒ์ผ์„ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ์Œ. ์ด ํŒŒ์ผ์„ ํˆด์— ๋„ฃ์–ด ํ™•์ธ ๊ฐ€๋Šฅ
    • trace.json : ์ปดํŒŒ์ผ์— ์†Œ์š”๋œ ์‹œ๊ฐ„ ์ค‘ ์˜ค๋ž˜ ๊ฑธ๋ฆฌ๋Š” ๋ถ€๋ถ„์„ ์ถœ๋ ฅ.
    • types.json : ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ธ์‹ํ•œ ํƒ€์ž…์˜ ๋ชฉ๋ก์„ ์ถœ๋ ฅ.

ํˆด์„ ์‚ฌ์šฉํ•ด์„œ ์„ฑ๋Šฅ ๋ฌธ์ œ ์ง„๋‹จ

  • @typescript/analyze-trace : CLI๋กœ trace๋ฅผ ๋ถ„์„ํ•˜์—ฌ hot spot ์‹๋ณ„ ๊ฐ€๋Šฅ
  • https://ui.perfetto.dev/ : GUI๋กœ ์ƒ์„ธํ•œ ํ™•์ธ์ด ๊ฐ€๋Šฅ

๊ฐœ์„ 

keyof JSX.IntrinsicElements;์€ 175๊ฐœ์˜ ํƒœ๊ทธ ์ด๋ฆ„์ด ๋“ค์–ด๊ฐ„ union type. ๋”ฐ๋ผ์„œ Row๋ฅผ ์ •์˜ํ•˜๋Š” ์ˆœ๊ฐ„ 175๊ฐœ์˜ ํƒœ๊ทธ๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋Š” ํƒ€์ž…์ด ์ •์˜๋จ

type Elements = keyof JSX.IntrinsicElements;
 
type FlexProps<E extends Elements> = E extends Elements
	? JSX.IntrinsicElements & { as?: E; gap?: number;}
	: never;
 
export const Row = <E extends Elements>({ as, ...props }:
									   PropsWithChildren<FlexProps<E>>) => {
	const &Element = as as React.ElementsType
	return <$Element {...props} />; 
}

์˜์ƒ์˜ ํ•ด๊ฒฐ์ฑ…์œผ๋ก  ๋‘๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์ œ์‹œํ•จ

Type Narrowing

์ผ๋ถ€ ํƒœ๊ทธ๋งŒ ์ง€์ •ํ•˜์—ฌ ํƒ€์ž…์˜ ๋ฒ”์œ„๋ฅผ ์ค„์ž„

type Elements = "div" | "section" | "label";

Dynamic inference

์ œ๋„ค๋ฆญ์„ ํ†ตํ•ด ํ•„์š”ํ•œ ํƒœ๊ทธ๋งŒ ์ง€์ •ํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•จ. Type Narrowing ๋ณด๋‹ค ๋‹ค์–‘ํ•œ ํƒœ๊ทธ์— ๋Œ€์‘๊ฐ€๋Šฅ

type Elements = keyof JSX.IntrinsicElements;
 
type ElementType<P = any> = {
	[K in Elements]: P extends JSX.IntrinsicElements[K]
}[Elements] | ((props: P) => JSX.Element);
 
type ElementProps<E extends ElementType> = E extends Elements ? JSX.IntrinsicElements[E] : {};
 
type FlexProps<E extends ElementType> = {as?: E};
 
type Props<E extends ElementType> = FlexProps<E> & Omit<ElementProps<E>, keyof FlexProps<E>>;
 
export const Row = <E extends ElementType>({ as, ...props }: Props<E>) => {
	const &Element = as || "div";
	return <$Element {...props} />; 
}

์œ„ ์ฝ”๋“œ๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์Œ

import { ComponentProps, ElementType } from "react";
 
type FlexProps<E extends ElementType> = {as?: E};
 
type Props<E extends ElementType> = FlexProps<E> & Omit<ComponentProps<E>, keyof FlexProps<E>>;
 
export const Row = <E extends ElementType>({ as, ...props }: Props<E>) => {
	const &Element = as || "div";
	return <$Element {...props} />; 
}

๊ทธ์™ธ ๊ฐœ์„ ๋ฒ•

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ ๊ถŒ์žฅํ•˜๋Š” ์ปดํŒŒ์ผ ๋˜๊ธฐ ์‰ฌ์šด ์ฝ”๋“œ ์ž‘์„ฑ๋ฒ• (๋งํฌ)

  • Preferring Interfaces Over Intersections
  • Using Type Annotations
  • Preferring Base Types Over Unions
  • Naming Complex Types