Repository navigation
Conversation
Copilot
AI
changed the title
[WIP] Copilot Request
Add Mar 9, 2026
identity modifier for function types to enable narrowing through repeated calls
Copilot
AI
changed the title
Add
Implement Mar 9, 2026
identity modifier for function types to enable narrowing through repeated callsidentity modifier for function type narrowing
identity modifier for function type narrowing…research doc Co-authored-by: kbrilla <[email protected]>
…ecks, diagnostics, and test cases Co-authored-by: kbrilla <[email protected]>
Adds detailed syntax examples for planned future phases: - Phase 4: Conservative-to-targeted migration path - Phase 5: Cross-binding invalidation (SolidJS/Preact signals) - Phase 6: invalidates on method declarations - Phase 7: mutates unified clause - Phase 8: --strictStable compiler flag - Phase 9: Keyed linked predicates (Map/Set narrowing) - Phase 10: Discriminated method unions (multi-predicate guards) - Phase 11: Getter property invalidation - Phase 12: Standard library annotations
After calling a setter/mutator with a known argument, the getter type should reflect the argument type (post-call narrowing), not revert to the full union type. Fixed 11 instances across 9 files where comments incorrectly showed "back to X | Y" instead of narrowing to the argument type.
Post-call argument narrowing is ALREADY IMPLEMENTED:
- setCount(20) narrows count() to number
- sig.set("hello") narrows sig.value() to string
- setCount(undefined) narrows count() to undefined
Updated Phase 5 with implementation status note and
expanded Phase 2 with positive narrowing case.
Phase 9 TypedMap now uses per-key syntax: stable[key] get(key: K) mutator[key] set(key: K, value: V) invalidates get[key], has[key] mutator clear() invalidates get, has (all keys) Phase 12 Map stdlib also updated with per-key syntax. Added implementation status notes to all phases: Phases 4-5: Already implemented Phases 6-12: Not implemented (with reasons)
Reorganized docs/index.md into clear categories: - Already Implemented (11 features) - Future Extensions (7 phases, with blocking reasons) - Open Questions & Decisions - Specifications & Proposals (with staleness warnings) - Research (historical reference) - Implementation Reviews - Risk Assessment - Cross-Language Survey (24 languages) Fixed HIGH priority status mismatches in 5 docs: - stable-pr-proposal.md: 5 update notes (CBI-1, declaration parity, post-call narrowing, super calls, SolidJS) - stable-phase8-proposal.md: Status → Implemented - research-solidjs-cross-binding.md: CBI-1 now implemented - stable-design-holes-analysis.md: Hole 3 resolved - stable-inheritance-research.md: Declaration parity + SEM-4
…signatures Add support for the invalidates clause on method declarations and method signatures (both interface methods and class methods). AST: Added LinksClause field to MethodSignatureDeclaration and MethodDeclaration with ForEachChild and Clone support. Parser: Parse invalidates clause after return type for method signatures and between return type and body for method declarations. Critical fix: set LinksClause before finishNode to ensure parent pointers are established for LinksClause identifier nodes. Checker: Updated isMutatorCallBoundary in flow.go to extract LinksClause from MethodDeclaration and MethodSignatureDeclaration in addition to FunctionTypeNode. Test covers 5 scenarios: 1. Selective invalidation via method-level invalidates 2. Multi-target method invalidation 3. Class method-level invalidates 4. Interface method vs function type dual syntax 5. Mutator method without invalidates (invalidates ALL stable)
Update PR description, index, and design decisions to reflect Phase 6 implementation (commit 61ba366).
Implement stable[key]/mutator[key] bracket syntax for per-key CFA
narrowing. This enables Map.has/Map.get-style narrowing where
get("x") and get("y") are independently narrowable references.
AST: Added KeyParameter field to FunctionTypeNode,
MethodDeclaration, and MethodSignatureDeclaration with
ForEachChild and Clone support.
Parser:
- New parseKeyParameterBinding() for [identifier] bracket syntax
- Extended parseFunctionOrConstructorType, parsePropertyOrMethodSignature,
and parseMethodDeclaration to parse stable[key]/mutator[key]
- Extended parseInvalidatesClause to parse invalidates get[key] bracket
- Updated lookahead functions for stable[key]/mutator[key] recognition
Checker (checker.go):
- Entry point now accepts keyed stable calls (1-arg with KeyParameter)
Checker (flow.go):
- isStableCallReference: accepts keyed stable calls with one argument
- isMatchingReference: extended CallExpression case for keyed calls —
matches if callees AND key arguments match (with literal comparison)
- writeFlowCacheKey: includes key argument in cache key for per-key
flow state tracking
- isMutatorCallBoundary: per-key invalidation — only invalidates when
mutator key argument matches the stable reference key argument
- signatureHasKeyParameter/isStableCallArgCountValid: new helpers
Checker (grammarchecks.go):
- Allow parameters on stable declarations with KeyParameter
Test covers 5 scenarios:
1. Basic per-key narrowing with literal keys (set/delete/clear)
2. Variable key reference narrowing
3. Independent simultaneous key narrowing
4. Per-key delete invalidation
5. Function type syntax with keyed stable
Update PR description, index, and design decisions to reflect Phase 9 implementation (commit 18f9a15).
Address soundness concern: mutator[key] without explicit invalidates clause was implicitly per-key against ALL stable endpoints, making it impossible to express mixed keyed/unkeyed invalidation across multiple stable methods on the same interface. Now per-key behavior is explicitly controlled by the invalidates clause: invalidates get[key] means per-key, invalidates get means all keys. The [key] references a parameter from the mutator method by name, which is resolved to a parameter index for argument comparison. Changes: - AST: Added LinksClauseKeyParamNames []string parallel to LinksClause - Parser: parseInvalidatesClause now captures key param names from [key] - Parser: Removed mutator[key] syntax (kept stable[key] only) - Checker: isMutatorCallBoundary uses invalidates clause key params to resolve per-key invalidation by parameter name Added test section 6 demonstrating multi-stable per-key control: setA invalidates only getA[key], setAll invalidates both, reset (unkeyed) invalidates all keys globally.
Remove mutator[key] syntax from examples. Per-key invalidation is now expressed via invalidates get[key] only.
Update Decided count to 6, Deferred to 8 in index.md. Mark LP-1 as implemented in PR description deferred table.
Add "Working Examples — What This PR Enables" section covering: 1. Basic stable narrowing 2. Mutator invalidation 3. Targeted invalidation with invalidates 4. Post-call argument narrowing 5. Linked type predicates 6. Cross-binding invalidation (SolidJS) 7. Exhaustive switch narrowing 8. Loop narrowing preservation 9. Callback argument transparency 10. Super call invalidation 11. Method-level invalidates 12. Keyed per-key narrowing (Map.has/Map.get) 13. Declaration parity — all forms
Analyzes whether invalidates is the right keyword since it both invalidates (resets narrowing) AND narrows (via post-call argument type). Compares mutator+invalidates vs unified mutates approach. Recommends updates as strongest alternative name.
kbrilla
added a commit
to kbrilla/solid
that referenced
this pull request
Mar 12, 2026
Demonstrates the stable/mutator/invalidates proposal from TypeScript-Go. Changes: - Accessor<T> = stable () => T in signal.ts and server/reactive.ts - 8 type-test scenarios in signals.stable-mutator.type-tests.ts - Cross-compiled tsgo binaries (darwin-arm64, darwin-amd64, linux-amd64) - STABLE-MUTATOR-DEMO.md with full documentation Companion PR: kbrilla/typescript-go#2
Demonstrates stable[key]/mutator/invalidates get[key] with reactive store patterns: per-key narrowing, cross-key independence, exhaustive switch, discriminated unions, and cross-store isolation.
…es get) Enables applying the mutator modifier to type references, not just inline function types. This supports patterns like SolidJS's Setter<T> which is a complex overloaded callable interface. Changes: - AST: Added WrappedType field to FunctionTypeNode - Parser: Recognize mutator followed by type reference identifier - Checker: Resolve wrapped type, handle CFA via tuple element lookup - Printer: Emit mutator TypeRef invalidates syntax - Test: 5 scenarios covering interfaces, overloads, type aliases, generic constraints, and explicit invalidation verification
- Add Working Example 14: Mutator on Type References (SolidJS Setter Pattern) - Add mutator TypeRef syntax to Supported Declarations reference - Update invalidates clause note: now supports TypeRef syntax - Add TYPEREF milestone to implementation milestones - Update Framework Coverage table for SolidJS - Update test count to 46 - Add SYN-7 DECIDED entry for mutator TypeRef AST representation - Update SYN-4 resolution to mention TypeRef support
Analyzes extending invalidates clause with post-narrowing targets: - invalidates get[key] = value (narrows to parameter type) - invalidates get[key] = undefined (narrows to literal type) - Covers Map, Set, WeakMap, WeakSet, DOM, URLSearchParams, Storage - Recommends invalidates ... = <type-or-param> syntax (Approach A) - Proposes Phase 13 for this extension, separate from Phase 12 stdlib
…tion Analyzes whether computed() signals can integrate with stable/mutator/invalidates: - Angular Signal<T> and WritableSignal<T> type architecture - Transitive invalidation is sound but infeasible at type level - Callback-body introspection violates core design principles - 5 design proposals analyzed with tradeoffs - Framework comparison: Angular, SolidJS, Vue, Preact, MobX - Recommends conservative blanket invalidation (already working) - No framework does type-level dependency tracking today
Analyzes current TypeScript behavior for array element access (`arr[0]`) narrowing vs `.at()` method calls (never narrowed). Explores how `stable[key]` would apply to Arrays: - Element access already narrowed by property CFA - `.at()` never narrowed (fresh call each time) - Cross-index writes do not invalidate (independent per-index narrowing) - Index-shifting methods (splice, unshift) do not invalidate — UNSOUND - Negative indices unsound with stable[key] due to dynamic resolution - TypedArrays are ideal candidates (fixed length, no shifting) - Recommends Array as Phase 14+, after Map and post-call narrowing
…ive index soundness Adds sections 14-18 to the array index narrowing research document: - CFA implementation details: how arr[0] narrows via isMatchingReference and writeFlowCacheKey (property-style key "symbol.0") - Why linking .at() and [] is architecturally expensive (different cache keys, different declared types, no [] equivalent for negative indices) - Tuple-specific analysis: .at() loses per-index precision (returns union of all elements + undefined), stable[key] cannot recover this - Complete negative index soundness analysis: method-based mutations coverable by mutator, but arr[i]=x, arr.length=0, delete are not - Same gaps exist for current arr[0] property narrowing — stable[key] is no worse and strictly better for method-based mutations - Updated recommendation: Option B (negative indices) is viable but Option A (positive-only) remains safer for initial implementation - Angular computed() dependsOn rejection reconfirmed with evidence - Three new open questions added
Adds sections 19-23 to the array index narrowing research document: - Tuple deep dive: tuples as near-perfect stable[key] candidates (fixed length at type level, no index shifting, negative indices are sound for tuples unlike arrays) - Empirical verification of tuple .at() behavior: always returns union of all elements + undefined, losing per-index precision - Stability matrix: Array vs Tuple vs ReadonlyArray vs ReadonlyTuple with soundness, value, and complexity ratings - stable[key] candidate ranking: readonly types rank highest (perfect soundness, zero invalidation) - TypeScript const/readonly CFA behavior: already handles property narrowing perfectly; method calls are the ONE remaining gap - Could tuples be automatically stable? Readonly types could get implicit stable semantics; propose hard-coded stdlib implicit stability for ReadonlyArray.at, ReadonlyMap.get, etc. - Summary table: stable[key] completes TypeScript const/readonly narrowing story by filling the method call gap
…arch Comprehensive analysis of 15 ngxtension utilities and their compatibility with stable/mutator/invalidates CFA modifiers. Tier 1 (high-value): SignalMap, SignalSet, signalSlice Tier 2 (medium): createNotifier, signalHistory, createSignal Tier 3 (covered by core): computedPrevious, derivedAsync, derivedFrom, etc. Tier 4 (irrelevant): extendedComputed (deprecated), createEffect Key finding: SignalMap is the single most compelling real-world use case for stable[key] — its per-key reactive tracking at runtime perfectly mirrors per-key narrowing invalidation at the type level. Includes deep dives on SignalMap CFA walkthrough, signalSlice state management with CFA, annotated .d.ts excerpts, and 6 open questions.
Fix nil pointer dereference in declaration transformer when processing mutator TypeRef wrapper FunctionTypeNodes (nil Parameters). Fix VisitEachChild for MethodSignatureDeclaration and MethodDeclaration to preserve KeyParameter, LinksClause, LinksClauseKeyParamNames when nodes are updated by visitors. Fix declaration transformer transformMethodSignatureDeclaration and transformMethodDeclaration to preserve custom fields after Update*. Fix parser to recognize mutator[key] bracket syntax (was only checking stable modifier, not mutator). Add CreateModifiersFromModifierFlags entries for stable and mutator. Add printer support for LinksClause and KeyParameter on method signatures, method declarations, and function types via emitLinksClause and emitKeyParameterBracket helpers. All .d.ts declaration output now correctly emits: - stable/mutator modifiers on all declaration kinds - invalidates clause with target names - stable[key]/mutator[key] bracket notation - invalidates get[key] per-key bracket notation - mutator TypeRef invalidates get wrapper syntax Test: stableModifierDeclarationEmit.ts covers 8 scenarios.
…dated notes Add Example 15 showing .d.ts declaration output for all syntax variants. Add DECL-EMIT implementation milestone. Fix outdated note about invalidates not being supported on methods. Update SYN-4 to DECIDED in deferred decisions. Update test count to 47. Add declaration emit and store pattern test entries.
…ator type display Fix FunctionTypeNode.VisitEachChild to visit KeyParameter, WrappedType, and LinksClause fields. Previously these were only in ForEachChild, causing panics in getTokenAtPosition (LSP hover/definition) when processing function types with stable/mutator/invalidates syntax. Fix nodebuilder to include stable/mutator modifiers in type display strings. Previously expanded function types showed () => T instead of stable () => T and mutator (v: T) => void. Add astnav tokens test for FunctionTypeNode with custom fields. Update 41 .types baselines to show stable/mutator in type display.
The fast path in getQuickTypeOfExpression returned the static return type from the signature, bypassing CFA narrowing for stable calls. This meant that .types baselines and LSP hover showed unnarrowed types like string | undefined instead of string inside guard scopes. Fix: check SignatureFlagsStable in getReturnTypeOfSingleNonGenericSignature and return nil to force fallthrough to checkCallExpression which applies CFA narrowing via getFlowTypeOfReference. Using getSingleSignature (lightweight) instead of getResolvedSignature (which triggered infinite recursion through CFA -> getTypeOfExpression -> getQuickTypeOfExpression -> isStableCallReference -> getResolvedSignature). 43 .types baselines updated to show narrowed return types.
When hovering over the callee of a stable call expression inside a guard scope, the tooltip now shows the CFA-narrowed return type alongside the declared type. For example: const count: stable () => number | undefined // narrowed call return: number This applies to both variable/property/accessor symbols and function/method symbols at call sites.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
stable,mutator,invalidates, and Linked Type PredicatesCFA narrowing through function calls — four cooperative mechanisms
Problem
TypeScript cannot narrow through repeated function calls. If
value()returnsstring | undefinedand you checkvalue() !== undefined, the compiler forgets this on the nextvalue()call. This is a major pain point for signal-based frameworks (Angular Signals, Preact Signals, MobX) where state is accessed through getter functions rather than properties. Property narrowing has worked for years — callable getter narrowing has not, despite being the dominant pattern in modern reactive frameworks.Real-World Issues Addressed
This proposal addresses a family of long-standing TypeScript issues with 1,350+ combined upvotes:
Repeated function call narrowing (TS-60948 — 105 👍, TS-57725 — 351 👍)
Angular Signal narrowing (TS-49161 — 149 👍)
Map has/get narrowing (TS-9619 — 179 👍, TS-13086 — 189 👍)
CFA trade-offs formalized (TS-9998 — 130 👍, 598 comments)
ahejlsberg's 2016 design question — "When a function is invoked, what should we assume its side effects are?" — remained unanswered for 9 years.
stable/mutatoris the first practical answer: functions can declare their relationship to narrowing explicitly.Correlated method types (TS-30581 — 159 👍)
Method Declaration Syntax (NEW — SYN-4)
stableandmutatornow work as method modifiers on method declarations and method signatures — not just function type annotations. This enables natural usage in classes, interfaces, and type literals:Super Call Invalidation (NEW — SEM-4)
In class hierarchies,
super.mutator()correctly invalidatesthis.stable()narrowing. Sincesuperandthisrefer to the same object instance, a super call to a mutator method must reset narrowing:What This PR Implements
Four declaration-site type modifiers that enable CFA narrowing through function calls:
stable— marks a callable getter as returning the same value on consecutive calls (absent mutation)mutator— marks a function as mutating backing state, resetting narrowinginvalidates— refinesmutatorto target specific stable endpointsmutator invalidatescall, the stable getter is narrowed to the argument's type (e.g.,setCount(20)narrowscount()tonumber)this.value() is Tsyntax for guard methods that narrow stable call resultsAll four are fully erasable (zero runtime overhead), declaration-site only, and structurally checked. The implementation includes a full test suite (42 test files) with zero regressions against the existing test baseline.
Implementation milestones:
stable/mutatormodifiers on method declarations and method signatures (class methods, interface methods, type literal methods)super.mutator()correctly invalidatesthis.stable()narrowing in class hierarchiesinvalidates readon a destructured setter targets the siblingreadaccessor, with full post-call narrowing and selective invalidationstable/mutatormodifiers behave across merged interfaces, intersections, and interface extensionDeclaration Parity
stable/mutatornow supported on ALL function-like declarations:stable function getValue(): T {}const f = stable function(): T {}const f = stable (): T => {}stable get value(): T(class + interface)mutator set value(v: T)(class + interface)stablerequires zero params (rejects setters),mutatorrejects gettersComplete Syntax Reference
stableModifier — Supported DeclarationsRestriction:
stablerequires zero parameters. Rejected on setters, constructors, and any function with parameters.mutatorModifier — Supported DeclarationsRestriction:
mutatoris rejected on get accessors (getters should not mutate state).invalidatesClauseNote:
invalidatesclause is currently only supported on function type syntax, not on method declarations or method signatures. For methods, the mutator resets all stable endpoints on the same receiver.Linked Type Predicates
Grammar Error Cases
Get / Set Accessor Parity
TypeScript property narrowing already preserves narrowing of
obj.valueacross function calls within a basic block. Thestable/mutatormodifiers on get/set accessors serve as:.d.tsfiles, informing downstream consumersFuture Phase Syntax (Under Consideration)
These entries show the design roadmap for
stable/mutator/invalidates. Phases 4–5 are already implemented in this PR; Phases 6–12 are future extensions under consideration.Phase 4: Conservative-to-Targeted Migration Path
Start with conservative invalidation (any method call resets narrowing), then gradually opt-in to targeted invalidation with
mutator:Phase 5: Cross-Binding Invalidation (SolidJS / Preact Signals)
Tuple-destructured APIs where getter and setter are separate bindings:
Phase 6:
invalidateson Method Declarations (SYN-4b)Selective invalidation directly on method declarations/signatures (not just function types):
Currently, method-level mutators reset ALL stable narrowing on the receiver. Selective
invalidateson methods requires AST struct changes and is deferred.Phase 7:
mutatesUnified Clause (SYN-1)A single
mutateskeyword could replace bothmutatorandinvalidates:Phase 8:
--strictStableCompiler Flag (SEM-5)An opt-in flag that reverses the default: without the flag, unmarked methods are transparent (don't invalidate); with the flag, unmarked methods are conservatively treated as mutators:
Phase 9: Keyed Linked Predicates (LP-1)
Guard methods that narrow stable endpoints with per-key parameter correlation. Uses
stable[key]/mutator[key]bracket notation to scope narrowing to specific key arguments, andinvalidates get[key]for per-key invalidation (vsinvalidates getwhich invalidates ALL keys):Phase 10: Discriminated Method Unions / Multi-Predicate Guards (LP-2)
Guard methods that narrow MULTIPLE stable endpoints simultaneously:
Phase 11: Getter Property Invalidation (LP-3)
invalidatestargeting getter properties (not just stable methods):Phase 12: Standard Library Annotations (ADO-1)
Built-in types annotated with
stable/mutator:Recommended Phased Introduction
Phase 1:
stablealone (conservative reset)Introduce
stablewith a conservative invalidation policy: any method call on the same receiver resets all stable narrowing on that receiver.Conservative reset means that even non-mutating calls like
sig.toString()would reset narrowing. This is safe by default — it's the same approach TypeScript uses for property narrowing (any call might invalidate).Scope: Parser + checker changes for
stablemodifier, conservative flow analysis.Phase 2:
mutatorandinvalidatesfor precise invalidationReplace conservative reset with explicit mutation marking. Only calls to
mutator-annotated methods reset narrowing.Scope: Parser + checker for
mutator/invalidates, targeted invalidation lists, multi-endpoint stores.Phase 3: Linked type predicates (independent extension)
Guard methods that narrow the return type of a stable method on the same receiver.
Scope: Parser for
this.method() is Treturn type syntax, checker predicate linking, guard invalidation rules.These are the design's known weaknesses. They should be evaluated openly.
1. Inverted Default — Optimistic vs. Pessimistic
Property narrowing is pessimistic: any function call resets narrowing on properties. The
stablesystem (withmutator) is optimistic: narrowing persists unless a method is explicitly markedmutator. This inverted default means forgettingmutatorsilently preserves narrowing that should be reset — a type hole. The property narrowing default is safer because it errs on the side of over-resetting.In practice, "I forgot to add
mutatorto a state-changing method" is a more likely developer error than "a Proxy changed the value behind my back." The optimistic default makes the common mistake silent.2. Two-Sided Trust Model
Both
stableANDmutatormust be correctly annotated for soundness. The compiler trusts the developer's annotations mechanically. If a method mutates backing state but isn't markedmutator, narrowing survives incorrectly. This is analogous to TypeScript's general trust model for type annotations (x: stringwhenxis actually anumber), but the blast radius of a missingmutatoris larger because it affects all stable narrowing on that receiver.3. SolidJS Cross-Binding Invalidation (Resolved)
SolidJS separates accessor and setter into different bindings:
Cross-binding invalidation is now implemented. Using named tuple label references in the
invalidatesclause, SolidJS-style APIs can express the read/write relationship:This uses destructuring provenance tracking — the checker maps
countto tuple labelreadandsetCountto labelwrite, soinvalidates readonwritecorrectly targetscount. See the Companion Documents section for the full research on 6 approaches evaluated.4. Structural Assignability Gap
mutatormarkers can be lost through structural widening. A structurally compatible assignment strips the mutation contract:This is the same category of issue as
readonlybeing lost through structural compatibility, but with soundness implications for CFA.5. Generic Interaction Unresolved
How
stablepropagates through generics, conditional types, and mapped types is an open question. For example:Partial<Signal<T>>preservestableonvalue?Pick<Signal<T>, 'value'>preservestable?ReturnType<Signal<T>['value']>understand stable call semantics?The current implementation handles direct usage correctly but does not define behavior for all type-level operations on stable types.
Framework Coverage
stableWorks?signal<T>()returns object with.set().valueproperty +.peek().peek()callable getterconst [get, set] = createSignal()ref().valueproperty accessAngular Template Caveat
Angular template narrowing depends on the Angular compiler's Template Type Check Block (TCB) generation. The TCB translates template expressions into TypeScript-checkable code. For stable narrowing to work in Angular templates (e.g.,
@if (sig()) { {{ sig() }} }), the TCB must generate code that the checker can narrow through stable calls. This may require coordination with the Angular compiler team and is not guaranteed to work out-of-the-box.Future Extensions (Not In This PR)
The following are explicitly not part of this proposal but are documented as future work:
has(key: K): this.get(key) is V— Map/Sethas()/get()narrowing with per-key invalidation trackingisResolved(): this.value() is T & this.error() is undefined— multi-predicate guards for async result patternspreserves): Inverse ofinvalidatesfor APIs where listing exceptions is more concisemutatesalternative syntax: Collapsingmutator+invalidatesinto a single clause (see full proposal §13)IsStable<T>): Type-level stable detectionOpen Design Questions
These questions remain unresolved and would benefit from TypeScript team input:
Syntax
mutator+invalidatesbe collapsed into a singlemutatesclause? (e.g.,set(v: T): void mutates value)readonly,abstract,static).mutatoris a noun. Should it bemutating?Semantics
--strictStablecompiler flag that treats ALL unmarked calls as potentially invalidating? (Reverses default-transparent)mutatorannotations?Map<K, V | undefined>,has(key)→get(key)narrowing would incorrectly narrowV | undefinedtoVCross-Binding
mutates read, getAdoption
Map.get,WeakRef.deref, DOM accessors) be annotatedstable?.d.tsthat work with bothstable-aware and older TS versions?stablebe allowed on functions with explicitthisparameter? Doesthistype serve as receiver for invalidation scoping?readonlyintegration — that the team would prefer?Deferred Decisions
These are deferred to future phases with rationale:
stablethe right name? Alternatives:getter,pure,cached,memoinvalidatesclause on method declarations (currently only on function types)stableon interface call signatures (interface { stable (): T; })stableis treated as method nameinvalidatesexclusive mode (sort: mutator () => void preserves length)stablepropagate through generics, conditional types, mapped types?T extends stable () => any ? true : falsediscriminate stable functions?has(key: K): this.get(key) is V— parameter correlationisOk(): this.value() is T & this.error() is undefinedinvalidatestarget getter properties?Companion Documents
All companion documents are located in the
docs/directory of this repository.docs/stable-pr-proposal.md— Full External ProposalThe primary proposal document (~2000 lines). Covers motivation from 5 real-world TypeScript issues (1,350+ combined upvotes), the three-modifier design (
stable,mutator,invalidates), linked type predicates, phased introduction plan (10 phases), soundness analysis, framework compatibility matrix, and 17 open design questions for the TypeScript team. This is the document intended for upstream submission.docs/stable-design-holes-analysis.md— Design Holes & Trust ModelAnalyzes the "default transparent" rule — why unmarked methods do NOT invalidate stable narrowing, the soundness implications of this optimistic default, and what
mutator/invalidatesactually provide beyondstablealone. Covers the lying-setter problem, structural assignability gaps, and the two-sided trust model.docs/stable-internal-design-document.md— Internal Technical SDDThe authoritative internal design document covering all 5+ implementation phases, parity tracking against TypeScript's property narrowing, conservative uncertainty-boundary invalidation, and tiered heuristic inference. This guided the actual Go implementation in
internal/checker/flow.goandinternal/checker/checker.go.docs/stable-modifier-spec.md— Formal SDD SpecificationFormal specification in SDD format with normative statements, phase boundary decisions, and checker behavior requirements. Defines exactly when narrowing is preserved, when it resets, how linked predicates interact with stable endpoints, and the constraint-overload post-call narrowing rules.
docs/ts-rejection-risk-assessment.md— Rejection Risk AssessmentRisk analysis of each proposal component against TypeScript Design Goals, TS team member quotes, and precedent from accepted features. Assesses
stablecore narrowing as low-risk (RyanCavanaugh actively engaged with upstream identity modifier proposal), with advanced features (linked predicates, constrained-overload) carrying higher risk.docs/research-solidjs-cross-binding.md— SolidJS Cross-Binding Invalidation ResearchDeep analysis of why SolidJS's
const [count, setCount] = createSignal()pattern cannot safely adoptstable— the read and write functions are separate bindings with no shared receiver. Evaluates 6 approaches: tuple index (mutates [0]), named channels, source interface extraction, named tuple label reference (mutates read) (recommended), heuristic inference, and object pattern. Estimates ~300-500 LOC for the recommended approach.docs/stable-design-decisions.md— Design Decisions RegisterConsolidated register of 30 open design decisions across 5 categories (Syntax, Semantics, Cross-Binding, Linked Predicates, Adoption). Each decision tracked with status (OPEN/RECOMMENDED/DEFERRED/DECIDED), phase impact, alternatives, and recommendation. Two decisions (SYN-4: method declarations, SEM-4: super call invalidation) are now DECIDED and implemented.
Other Research Documents (in
docs/)stable-phase8-proposal.md— Phase 8+ proposal covering keyed linked predicates, discriminated method unions, exclusive invalidation (preserves), and conditional type discriminationstable-modifier-research.md— Initial research: cross-language survey (Rust, Kotlin, Swift, C++), prior art analysis, and modifier naming alternativesstable-inheritance-research.md— Class hierarchy behavior: virtual dispatch, override narrowing, covariant/contravariant method overridesresearch-map-has-get-narrowing.md— Maphas()/get()narrowing analysis for Phase 9 keyed predicatesstable-heuristic-uncertainty-boundaries-research.md— Uncertainty boundary classification: which constructs reset stable narrowing and whyKey Test Files
42 test files in
testdata/tests/cases/compiler/:Core narrowing:
stableModifierNarrowing.ts— basic stable narrowing and resetstableModifierBoundaries.ts— uncertainty boundaries and reset pointsstableModifierSignalPatterns.ts— real-world signal API patternsstableModifierParity.ts/stableModifierSubmoduleParity.ts— getter/setter parityEquality and control flow:
stableModifierEqualityChain.ts— discriminant-style narrowingstableModifierExhaustiveSwitch.ts— exhaustive switch on stable callsstableModifierAdvancedLoops.ts— loop narrowing behaviorMutator and invalidation:
stableModifierMutatorBasic.ts— basic mutator resetstableModifierMutatorLinks.ts—invalidatesclause with targeted resetstableModifierMutatorErrors.ts— validation diagnosticsstableModifierPostCallNarrowing.ts— post-call narrowing after constrained writesstableModifierCrossBinding.ts— cross-binding invalidation via named tuple labels (SolidJS pattern)Linked predicates:
stableModifierLinkedPredicates.ts—this.value() is Tlinked type predicatesstableModifierAssertionGuards.ts— assertion-style guardsMethod declarations and super calls:
stableModifierMethodDeclarations.ts— stable/mutator on method declarations and method signaturesstableModifierSuperCalls.ts— super call invalidation in class hierarchiesEdge cases:
stableModifierInterfaceMerging.ts— interface merging and intersection behavior with stable/mutator modifiersstableModifierClosures.ts— closure capture behaviorstableModifierOptionalChaining.ts/stableModifierAdvancedOptionalChain.tsstableModifierCrossModule.ts— cross-module stable referencesstableModifierErrors.ts/stableModifierDiagnostics.ts— error reportingstableModifierEmit.ts— erasure correctnessstableModifierDeclarationParity.ts— 11 sections: all declaration kinds, grammar errors, namespace supportHeuristic tiers and boundaries:
stableModifierTier1Writes.ts— tier 1 write invalidationstableModifierTier2.ts— tier 2 heuristic inferencestableModifierStandaloneCallBoundary.ts— standalone call boundary behaviorstableModifierMethodCallBoundary.ts— method call boundary behaviorstableModifierValueTypeBoundary.ts— value type boundary behaviorGetter analysis:
stableModifierGetterCorpus.ts— getter pattern corpusstableModifierGetterParitySweep.ts— getter parity sweep testsstableModifierGetterMissingMatrix.ts— getter missing matrix coverageAdvanced patterns:
stableModifierAdvancedCallbacks.ts— advanced callback behaviorstableModifierMultiArgCallback.ts— multi-argument callback patternsstableModifierConstrainedOverload.ts— constrained overload resolutionstableModifierGenericDiscriminant.ts— generic discriminant narrowingstableModifierInOperator.ts—inoperator narrowing with stableDiagnostics and edge cases:
stableModifierBareParameter.ts— bare parameter diagnosticsstableModifierHeuristicDiagnostics.ts— heuristic diagnostic messagesstableModifierP8Conservative.ts— phase 8 conservative modePipeline Status
All pass:
npx hereby buildnpx hereby testnpx hereby lintnpx hereby format