Skip to content

perf(react): type JSX children so the default overload matches them as a subtype - #1111

Open
owjs3901 wants to merge 1 commit into
mainfrom
perf/react-type-check
Open

owjs3901 wants to merge 1 commit into
mainfrom
perf/react-type-check

Conversation

@owjs3901

@owjs3901 owjs3901 commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Next's TypeScript phase is slower for Devup UI apps than for Tailwind ones. This PR finds where the type-check time goes and removes the largest part of it, without changing which programs the types accept or reject.

Where the time goes

Measured with tsc --extendedDiagnostics and --generateTrace (TS 7) on the large benchmark app and on single-construct apps of 100 to 3,000 elements:

  • Per-element overload fallthrough (the biggest cost). Components such as Box have three overloads: the default element, the polymorphic as one (generic), and the default again. With more than one overload, the checker first tries a subtype pass. A JSX element is a ReactElement<any, any>, and any is assignable to ReactNode but not its subtype. So every Box, Flex, Text... with element children failed the subtype pass on its default overload. The checker then inferred and checked the polymorphic overload, then the trailing default, and only took the first overload in the assignability pass. This cost about 16 extra types and 14 instantiations per element. On the large app it doubled the types the checker creates (66,143, against 36,187 once it is fixed).
  • One-time warm-up per checker (about 16k instantiations). About 14k of them build the _hover/_groupHover... keys of the selector props (CamelCase/PascalCase over the csstype pseudo lists), and the rest come from Merge/Omit over the CSS properties. tsgo runs 4 checkers, and each one pays this once.
  • StyleOrder (Range<255>) creates 35k types, but only when styleOrder is used.

Change

The default props type children as C | JSX.Element | readonly (...)[], so JSX children match the default overload as a subtype. This is used only where C (the element's own children) already accepts every value of that union, so the props accept and reject the same values on the web and on React Native.

New type tests check that:

  • the props of div/span/button/img/input stay the same as before: the same keys and optionality, identical types for every prop, and the same values for children. This holds on the web and with the React Native augmentation.
  • the children forms are still accepted (an element, several elements, text, mapped arrays, nested arrays), and an object or a function child is still rejected on the web.

All the new tests also pass against the types on main.

Results (large benchmark app, alternating A/B runs, medians)

before after
Next build "TypeScript" phase (20 runs each) 474 ms 412 ms
tsc on the app project, the command Next runs: check time (20 runs) 106.5 ms 82 ms
same, total time 219 ms 193.5 ms
same, --checkers 1 check time (12 runs, generated app copy) 240 ms 168 ms
types / instantiations (deterministic) 66,143 / 138,890 36,187 / 123,308

Tried and not kept

  • Flattening the default props into one interface per element, so the checker walks an interface once instead of each intersection member and then the whole. This was not faster in TS 7, and in isolated tests it was slower.
  • Hard-coding the selector key lists, to skip the CamelCase work during warm-up. It cut 8.7k instantiations but saved only about 6% of check time, within noise. It would also mean keeping a 212-key list in sync with csstype-extra.
  • NoInfer on the polymorphic overload's props. It saved about 14% alone, and nothing on top of this change.

요약

Devup UI 앱의 Next TypeScript 단계가 Tailwind 앱보다 느립니다. 이 PR은 타입 검사 시간이 어디에 쓰이는지 찾고, 타입이 받아들이거나 거부하는 프로그램을 바꾸지 않고 그중 가장 큰 부분을 없앱니다.

시간이 쓰이는 곳

대형 벤치마크 앱과 요소 100~3,000개짜리 단일 구성 앱에서 tsc --extendedDiagnostics와 --generateTrace(TS 7)로 측정했습니다.

  • 요소마다 일어나는 오버로드 폴스루(가장 큰 비용). Box 같은 컴포넌트에는 오버로드가 셋 있습니다. 기본 요소, 다형 as(제네릭), 다시 기본 요소입니다. 오버로드가 둘 이상이면 체커는 먼저 서브타입 패스를 시도합니다. JSX 요소는 ReactElement<any, any>이고, any는 ReactNode에 할당은 되지만 서브타입은 아닙니다. 그래서 요소 자식을 가진 모든 Box, Flex, Text...가 기본 오버로드의 서브타입 패스에서 실패했습니다. 그러면 체커는 다형 오버로드를 추론·검사하고, 이어서 마지막 기본 오버로드를 검사한 뒤에야 할당 패스에서 첫 오버로드를 택했습니다. 요소마다 타입 약 16개, 인스턴스화 14개가 더 들었습니다. 대형 앱에서는 체커가 만드는 타입이 두 배가 됐습니다(수정 전 66,143개, 수정 후 36,187개).
  • 체커마다 한 번 드는 워밍업(인스턴스화 약 16k). 그중 약 14k는 셀렉터 props의 _hover/_groupHover... 키를 만드는 데 듭니다(csstype 의사 클래스 목록에 대한 CamelCase/PascalCase). 나머지는 CSS 속성에 대한 Merge/Omit에서 나옵니다. tsgo는 체커 4개를 돌리고, 체커마다 이 비용을 한 번씩 냅니다.
  • StyleOrder(Range<255>)는 타입 35k개를 만들지만 styleOrder를 쓸 때만입니다.

변경

기본 props가 children을 C | JSX.Element | readonly (...)[]로 타이핑해서, JSX 자식이 기본 오버로드에 서브타입으로 맞습니다. 요소 자신의 children인 C가 이 유니온의 모든 값을 이미 받는 경우에만 씁니다. 그래서 웹과 React Native에서 props가 받아들이고 거부하는 값은 그대로입니다.

새 타입 테스트는 다음을 확인합니다.

  • div/span/button/img/input의 props가 이전과 같습니다. 키와 선택성이 같고, 모든 prop의 타입이 동일하며, children이 받는 값이 같습니다. 웹에서도, React Native 보강을 적용해도 마찬가지입니다.
  • 자식 형태(요소 하나, 여러 요소, 텍스트, map 배열, 중첩 배열)는 여전히 받아들이고, 웹에서 객체나 함수 자식은 여전히 거부합니다.

새 테스트는 모두 main의 타입으로도 통과합니다.

결과 (대형 벤치마크 앱, A/B 교대 실행, 중앙값)

이전 이후
Next 빌드 "TypeScript" 단계 (각 20회) 474 ms 412 ms
앱 프로젝트에 대한 tsc(Next가 실행하는 명령) 검사 시간 (20회) 106.5 ms 82 ms
같은 명령의 전체 시간 219 ms 193.5 ms
--checkers 1 검사 시간 (12회, 생성한 앱 사본) 240 ms 168 ms
타입 / 인스턴스화 (결정적) 66,143 / 138,890 36,187 / 123,308

시도했지만 넣지 않은 것

  • 기본 props를 요소별 인터페이스 하나로 평탄화하기. 체커가 교차 타입의 각 멤버와 전체를 따로 훑는 대신 인터페이스를 한 번만 훑게 하려는 것이었습니다. TS 7에서는 빠르지 않았고, 단독 테스트에서는 더 느렸습니다.
  • 셀렉터 키 목록 하드코딩. 워밍업의 CamelCase 작업을 건너뛰려는 것이었습니다. 인스턴스화는 8.7k 줄었지만 검사 시간은 약 6%만 줄어 노이즈 범위였습니다. 게다가 212개 키 목록을 csstype-extra와 계속 맞춰야 합니다.
  • 다형 오버로드 props에 NoInfer 적용. 단독으로는 약 14% 줄었지만, 이 변경 위에서는 효과가 없었습니다.

🤖 Generated with Claude Code

…s a subtype

With more than one overload, the checker first looks for a signature in a
subtype pass. A JSX element is a ReactElement<any, any>, and `any` is
assignable to ReactNode but not its subtype, so every Box, Flex, Text... with
element children failed the subtype pass on its default overload, and the
checker inferred and checked the polymorphic `as` overload and the trailing
default before it took the first one in the assignability pass.

The default props now type `children` as `C | JSX.Element | readonly
(...)[]`, used only where `C` accepts every value of that union, so the props
accept and reject the same values while JSX children match as a subtype.

Large benchmark app, 20 alternating runs, medians: tsc check 107 -> 82 ms,
Next's TypeScript phase 474 -> 412 ms; types 66,143 -> 36,187.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Dec 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant