ReviewOS

stacks/stx

components: defineProps<T>() / defineEmits<T>() for typed component contracts

#1740
Closed glennmichael123 opened this 22 days ago · 2 comments
22 days ago

Problem

stx components today use an untyped $props.X bag in <script server>:

<script server>
export const src = $props.src || ''
export const alt = $props.alt || ''
export const fallback = $props.fallback || '/images/default.svg'
export const className = $props.className || ''
</script>

Problems:

  1. No call-site validation. <SafeImage src={someBoolean} /> compiles. <SafeImage src="x" srx="typo" /> compiles. Wrong types reach <img src=...> and the browser silently renders an empty image or garbage.
  2. No discoverability. The list of accepted props lives in <script server> body; the caller has to read the component source. There's no editor surface for "what props does <Notification> take?"
  3. No autocomplete. Typing <SafeImage in an editor gets you nothing. Vue's defineProps<{ src: string }>() gives you autocomplete on every prop name + type validation on every value.
  4. Defaults are stringly. $props.src || '' collapses 0, false, null, '' into the fallback. For a numeric prop like count={0}, the default-coalesce silently swaps it for the fallback.
  5. No required vs optional distinction. Every prop is treated as optional with || default. No way to express "this prop is required and must be a number ≥ 0."

The first three are DX gaps. The last two are correctness gaps.

Proposed API

Mirror Vue 3 SFC's defineProps shape so adopters from Vue land transfer immediately:

<script server>
interface Props {
  src: string                          // required
  alt?: string                         // optional
  fallback?: string                    // optional with default
  fallbackClassName?: string
  className?: string
}

const props = defineProps<Props>({
  fallback: '/images/safe-image-default.svg',
  alt: '',
})
</script>

<img
  src="{⁠{ props.src }}"
  alt="{⁠{ props.alt }}"
  class="{⁠{ props.className }}"
  data-fallback="{⁠{ props.fallback }}"
  ...
/>

Build-time SFC compilation:

  • Generates a JSON schema describing prop shape at component file path
  • Emits .d.ts file alongside the component so editors can autocomplete callsites
  • Validates at call site: <SafeImage src={123} /> becomes a TS error, not silent runtime garbage

Runtime SSR:

  • props.src accesses the validated value (with default applied for optional props)
  • Type assertions still hold (src is string, narrowed)

Sibling APIs (paired)

// Events typed similarly
interface Emits {
  (e: 'close'): void
  (e: 'submit', payload: { value: string }): void
}
const emit = defineEmits<Emits>()
emit('submit', { value: 'hi' })   // typed
emit('subm', ...)                  // TS error

// Slots typed
interface Slots {
  default: () => unknown
  header?: (props: { title: string }) => unknown
}
const slots = defineSlots<Slots>()

Prior art

  • Vue 3 SFC — defineProps<T>() is the de-facto standard
  • React — interface Props {}; function Comp(props: Props) — same TS-validated shape
  • Svelte 5 runes — let { src, alt = '' } = $props() with TS inference
  • Solid — (props: Props) => JSX with full inference
  • Qwik — component$((props: Props) => ...)

Every modern framework has typed props. stx is the only one that doesn't.

Impact

  • Authoring DX: high. Adding a new component goes from "read another component's source to discover convention" to "let the compiler tell me what's required."
  • Call-site safety: high. Wrong-shape calls become TS errors.
  • Migration ergonomics from Vue/React: huge. The bigger lift for an adopter from Vue land today is "wait, where's defineProps?"

Phasing

  • Phase 1: Compile-time validation of defineProps<T>() shape — generates .d.ts for the component, no runtime change
  • Phase 2: Call-site type-check (the JSX-equivalent <SafeImage src={...} /> validates against the generated .d.ts)
  • Phase 3: defineEmits<T>() + defineSlots<T>() for the full contract surface
  • Phase 4: defineExpose<T>() for ref-accessed methods (already partially supported via current shape)

Happy to PR Phase 1.

22 days ago

Shipped in e90d91f — the runtime + typing half of this issue (effectively Phases 3–4, plus the correctness win from point 4):

  • defineProps<T>() already returned a typed T; defineEmits<E>() and defineExpose<T>() were already typed too. The gap was defineSlots<T>(), now added and wired everywhere the sibling macros live (composition-api, barrel export, client auto-imports, runtime destructures, signal-API regex, server sandbox, window.stx, stx.d.ts).
  • Defaults never collapse falsy values (point 4). A default applies only when the prop is undefined, so a passed 0 / false / '' is kept. This now holds identically across all three impls — src/props.ts (module), src/variable-extractor.ts (<script server> sandbox), and src/signals.ts (client window.stx). The server sandbox previously ignored the options-style defaults arg entirely; it now honors defineProps({ count: { default: 0 } }) like the other two. Pinned by test/composition/typed-contracts.test.ts (9 tests).
  • Docs: typed-contracts section in docs/guide/components.md.

One API note on the proposed shape: the headline example uses a single-call plain-defaults form:

const props = defineProps<Props>({ fallback: '/images/...', alt: '' })

All three impls treat defineProps's argument as Vue options-style ({ key: { default } }), not plain defaults — so that single-call form silently applies no defaults. The Vue-canonical (and now correctness-guaranteed) way to get plain defaults is:

const props = withDefaults(defineProps<Props>(), { fallback: '/images/...', alt: '' })

That's what the docs recommend. I kept parity with Vue rather than adding an ambiguous single-call plain-defaults overload (a plain object default is indistinguishable from an options descriptor).

Remaining (keeping this open): Phase 1/2 — compile-time .d.ts generation from defineProps<T>() + call-site validation so <SafeImage src={123} /> becomes a TS error. That's a build-tooling effort, separate from the runtime work above. Your offer to PR Phase 1 still stands as the natural next step.

22 days ago

Public-surface fix landed in 31f5546.

The actual issue: defineProps<T>() (and all the helpers — withDefaults, prop, required, etc.) already existed in src/props.ts since the original Phase 4 work. They were just commented out of src/index.ts because PropType (constructor union) clashed with ./types' PropType (string union). So import { defineProps } from 'stx' failed to resolve in editors, even though every existing test and code sample assumed it worked.

Shipped: selective re-export from main entry:

  • defineProps / definePropsWithValidation / withDefaults
  • processComponentProps
  • prop / required / optional / validated
  • oneOf / arrayOf / shape
  • types: PropOptions, PropsDefinition, ExtractPropTypes, PropValidationError, PropValidationResult

Intentionally NOT re-exported to avoid clobbering:

  • PropType (use import type { PropType } from 'stx/props' — already routable via the ./* glob in package.json)
  • EmitFn / defineEmits from props.ts (dead duplicates — the canonical ones come from ./composition-api, already exported)

The runtime side (defineProps reading __STX_CURRENT_PROPS__, defaults coalescing for undefined-only, withDefaults non-destructive merge) was already correct. Added 10 tests against the public surface and verified the runtime path. Composition suite: 28/28.

Deferred (Phase B):

  • Build-time .d.ts emit alongside each .stx so callers get autocomplete on <SafeImage ... /> — that's the larger compiler lift hinted in the issue, separate work.
  • Numeric-prop default coalescing fix (the count={0} → fallback footgun) is a separate code change in the call-site processing path, not the API surface.

Closing — the headline "callers can't import the API" gap is fixed.

Sign in to comment on this issue.