React에 있는 도서관에서 가끔 볼 수 있는 걸 찾아봤어요.분위기 속에서 JS를 써주시는 분들께 보내드리도록 하겠습니다.

일의 발단


<Alert variant="danger" onClose={() => setShow(false)} dismissible>
  <Alert.Heading>...</Alert.Heading>
  <p>
    str...
  </p>
</Alert>
React Bootstrap을 사용할 때 이런 코드를 보았다고 생각해요.<Alert.Heading>뭐야...
export namespace Alert {
  export const Heading = (props) => <>...</>
}
같은 설치?
그런데 이렇게 하면 <Alert {...props}>...</Alert>라고 쓸 수가 없어...

React Component가 아니라 JavaScript라면.


클릭 후 Stack Overflow에 다음 코드가 적혀 있는 것을 발견했습니다.

// module.tsx
export const Component = () => <>...</>

Component.Body = () => <>...</>

// main.tsx
import ...

const Main = () => {
  return (
    <Component>
      <Component.Body />
    </Component>
  )
}

export default Main
왜 이렇게 썼을까요?
분위기 속에서 자바스크립트를 쓴 나는 모른다.
일반적인 함수로 같은 일을 해 보았다.
const hello = (name: string) => `hello, ${name}`
hello.world = () => hello('world')

console.log(hello('john')) // hello, john
console.log(hello.world()) // hello, world
기대에 따라 집행한다.
여기서 람다식을 자주 사용하던 내가 평소 깨닫지 못했던 일이 떠올랐다.
JavaScript의 함수는 첫 번째 레벨 객체입니다.
함수는 대상, 즉 대상이기 때문에 방법을 생성할 수 있다.
타입 알리스를 쓰면 이런 느낌이에요.
type Hello = {
  (name: string): string;
  world(): string;
};

const hello: Hello = (name) => `hello, ${name}`;
hello.world = () => hello("world");

console.log(hello("john")); // hello, john
console.log(hello.world()); // hello, world

좋은 웹페이지 즐겨찾기