docs(rules): update TypeScript and Angular rules for TS 7 and trim duplicates

TypeScript 7.0 ships the native compiler as tsc and drops options
deprecated in 6.0. Angular 22 still requires TypeScript >=6.0.0 <6.1.0,
so both rule sets now warn against moving Angular projects to TS 7, and
the Angular index asks to check the Angular version first.

TypeScript runtime safety adds error handling (Error objects only,
cause chaining, unknown in catch, one error model per layer, no
swallowed errors) plus exact decimals for money, ISO 8601 UTC dates, and
Intl formatting. Angular adds per-route SSR render modes, a global
ErrorHandler with provideBrowserGlobalErrorListeners, and translatable
text with locale-aware formatting.

Generic guidance that the TypeScript, refactoring, and UI/UX rules
already cover is removed from the Angular rules, which shrink by about
7.5 percent despite the additions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Julian LechnerandClaude Opus 5.5 committed 2026-11-18 10:08:25 +01:00
1 parent 368cf5ee4a
commit b6c33780c3
9 files changed
+43 -114

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# Angular Rules # Angular Rules
For Angular work, open the focused topic rule that matches the change. Angular code is TypeScript: load the matching TypeScript topic rules (`rules/typescript/index.md` / `rules-typescript`) as well. Load the security and accessibility rule when the change renders untrusted content, binds HTML or URLs, configures HTTP security or tokens, or builds interactive controls. For Angular work, check the Angular version in `package.json` first, then open the focused topic rule that matches the change. Angular code is TypeScript: load the matching TypeScript topic rules (`rules/typescript/index.md` / `rules-typescript`) as well. Load the security and accessibility rule when the change renders untrusted content, binds HTML or URLs, configures HTTP security or tokens, or builds interactive controls.
| Topic | Codex rule | Claude skill | | Topic | Codex rule | Claude skill |
| --- | --- | --- | | --- | --- | --- |
@@ -6,19 +6,12 @@ Apply these rules when creating or changing Angular components, directives, sign
* Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it. * Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it.
* Keep components small; move substantial business logic to a focused service or domain layer. * Keep components small; move substantial business logic to a focused service or domain layer.
* Keep dependencies explicit and follow the feature architecture. Avoid god components, god services, unnecessary wrappers, and abstractions without a concrete need.
* Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to, in both zone.js and zoneless applications. * Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to, in both zone.js and zoneless applications.
* Keep component state minimal and prefer immutable state updates. * Keep component state minimal, update it immutably, and never mutate shared state directly.
* Avoid direct mutation of shared state.
* Keep inputs and outputs strongly typed.
* In new code on Angular 19+, use `input()` and `input.required()`, `output()` (an `OutputEmitterRef`, not a signal), `model()` for intended two-way bindings, and signal queries (`viewChild`, `viewChildren`, `contentChild`, `contentChildren`). Keep `@Input`, `@Output`, and decorator queries only where the surrounding code uses them. * In new code on Angular 19+, use `input()` and `input.required()`, `output()` (an `OutputEmitterRef`, not a signal), `model()` for intended two-way bindings, and signal queries (`viewChild`, `viewChildren`, `contentChild`, `contentChildren`). Keep `@Input`, `@Output`, and decorator queries only where the surrounding code uses them.
* Use the `host` object in component metadata instead of `@HostBinding` and `@HostListener` in new code. * Use the `host` object in component metadata instead of `@HostBinding` and `@HostListener` in new code.
* Avoid unnecessary two-way binding. * Prefer explicit data flow: inputs down, events up. Avoid unnecessary two-way binding, component coupling, and exposed internal state.
* Avoid unnecessary component-to-component coupling. * Use lifecycle hooks only when required, and keep constructors free of complex initialization.
* Prefer explicit data flow from parent to child and explicit events upward.
* Do not expose internal component state unnecessarily.
* Use lifecycle hooks only when required.
* Avoid complex initialization logic inside constructors.
## Change Detection ## Change Detection
@@ -40,9 +33,6 @@ Apply these rules when creating or changing Angular components, directives, sign
## DOM and Browser APIs ## DOM and Browser APIs
* Prefer Angular APIs and declarative templates over direct DOM manipulation. * Prefer Angular APIs and declarative templates over direct DOM manipulation; use `Renderer2` only when a rendering abstraction is actually needed.
* Use `Renderer2` only when direct rendering abstraction is actually needed.
* Avoid accessing globals directly when it harms testability or SSR compatibility.
* When the application uses SSR, guard `window`, `document`, `localStorage`, and similar browser-only APIs with `isPlatformBrowser`, or run DOM access in `afterNextRender` or `afterRenderEffect`, which run only in the browser. * When the application uses SSR, guard `window`, `document`, `localStorage`, and similar browser-only APIs with `isPlatformBrowser`, or run DOM access in `afterNextRender` or `afterRenderEffect`, which run only in the browser.
* Clean up event listeners, observers and timers. * Clean up event listeners, observers, and timers, and avoid layout thrashing in performance-sensitive code.
* Avoid layout thrashing in performance-sensitive code.
@@ -6,23 +6,14 @@ Apply these rules when building Angular forms, validation, routes, guards, or re
* Follow the form approach the project uses. For non-trivial forms, use typed reactive forms (`FormGroup`, `FormControl`, `NonNullableFormBuilder`; `nonNullable` controls where reset should restore the initial value) and never `Untyped*` classes in new code. * Follow the form approach the project uses. For non-trivial forms, use typed reactive forms (`FormGroup`, `FormControl`, `NonNullableFormBuilder`; `nonNullable` controls where reset should restore the initial value) and never `Untyped*` classes in new code.
* Signal forms (`@angular/forms/signals`) are stable since Angular 22. Use them for new forms only when the project is on 22+ and has adopted them; do not migrate existing forms unasked. * Signal forms (`@angular/forms/signals`) are stable since Angular 22. Use them for new forms only when the project is on 22+ and has adopted them; do not migrate existing forms unasked.
* Keep validation rules centralized and reusable where practical. * Keep validation rules centralized and reusable, and keep form state separate from domain state when useful. The UI/UX forms rule covers error display and input preservation.
* Client-side validation is user experience; the server must validate every submission. Never treat client-side validation as a security boundary. * Client-side validation is user experience; the server must validate every submission. Never treat client-side validation as a security boundary.
* Keep form state separate from domain state when useful.
* Avoid large components that combine layout, validation, persistence and business logic.
* Display validation errors consistently.
* Preserve user input when recoverable errors occur.
## Routing ## Routing
* Keep route definitions explicit and predictable. * Keep route definitions explicit, and lazy load larger feature areas with `loadComponent` or `loadChildren` pointing to standalone route arrays.
* Prefer lazy loading for larger feature areas with `loadComponent` or `loadChildren` pointing to standalone route arrays.
* Write new guards and resolvers as functions (`CanActivateFn`, `ResolveFn`); keep class-based guards where the project uses them, since they remain supported. * Write new guards and resolvers as functions (`CanActivateFn`, `ResolveFn`); keep class-based guards where the project uses them, since they remain supported.
* Use `withComponentInputBinding()` to bind route parameters to component inputs where the project enables it. * Use `withComponentInputBinding()` to bind route parameters to component inputs where the project enables it.
* Avoid loading large feature bundles eagerly without need. * Use route guards only for navigation behavior, not as a security boundary; enforce authorization on the backend. Keep resolvers focused and navigation free of expensive work.
* Use route guards only for navigation behavior, not as a security boundary.
* Authorization must still be enforced on the backend.
* Keep resolvers focused.
* Avoid expensive work during navigation unless required.
* Route and query parameters arrive as `string | null`. Parse and validate them before use and treat them as untrusted input. * Route and query parameters arrive as `string | null`. Parse and validate them before use and treat them as untrusted input.
* Do not rely on client-side routing state for sensitive authorization decisions. * With SSR, set the render mode per route in `app.routes.server.ts` (`ServerRoute` with `RenderMode.Prerender` for static pages, `RenderMode.Server` for per-request content, `RenderMode.Client` for client-only pages), registered through `provideServerRendering(withRoutes(...))`.
+1 -2
View File
@@ -10,8 +10,7 @@ Apply these rules when writing or changing RxJS streams, subscriptions, or signa
* Avoid nested `subscribe`. * Avoid nested `subscribe`.
* Avoid manual subscriptions where `async`, signals or framework helpers are sufficient. * Avoid manual subscriptions where `async`, signals or framework helpers are sufficient.
* Bind every manual subscription's lifetime with `takeUntilDestroyed` or equivalent Angular lifecycle integration to avoid leaks. * Bind every manual subscription's lifetime with `takeUntilDestroyed` or equivalent Angular lifecycle integration to avoid leaks.
* Use the correct flattening operator for the required semantics. * Choose the flattening operator for its semantics; `switchMap`, `mergeMap`, `concatMap`, and `exhaustMap` are not interchangeable.
* Do not use `switchMap`, `mergeMap`, `concatMap` or `exhaustMap` interchangeably.
* Avoid unnecessary `Subject` usage. * Avoid unnecessary `Subject` usage.
* Prefer exposing observables instead of exposing mutable subjects. * Prefer exposing observables instead of exposing mutable subjects.
* Prefer `BehaviorSubject` only when a current value is actually required. * Prefer `BehaviorSubject` only when a current value is actually required.
@@ -1,44 +1,22 @@
# Angular Dependency Injection, Services, and HTTP # Angular Dependency Injection, Services, and HTTP
Apply these rules when creating Angular services, configuring dependency injection, or calling HTTP APIs. Apply these rules when creating Angular services, configuring dependency injection, or calling HTTP APIs. The TypeScript modeling and runtime-safety rules cover contracts and validation; this file adds Angular specifics.
## Dependency Injection ## Dependency injection and services
* Prefer Angular dependency injection for application services.
* Keep injected dependencies minimal.
* Avoid service locator patterns.
* Prefer the `inject()` function over constructor parameter injection, as the Angular style guide recommends since v20; keep constructor injection where the surrounding code consistently uses it. * Prefer the `inject()` function over constructor parameter injection, as the Angular style guide recommends since v20; keep constructor injection where the surrounding code consistently uses it.
* Do not inject services that are not used. * Scope services intentionally. Use root singletons only for truly shared, stateless, or coordinated state, and never store request- or component-specific mutable state in them.
* Scope services intentionally. * Use injection tokens for configuration or real abstractions; do not add interfaces only to satisfy dependency injection.
* Prefer application-wide singletons only for truly shared stateless or coordinated state. * Keep services focused, expose readonly state to consumers, and separate API access, domain logic, and UI state where practical. Do not use services merely to move poorly structured component code elsewhere.
* Avoid storing request-specific or component-specific mutable state in root services.
* Use injection tokens for configuration or abstractions where appropriate.
* Do not create interfaces only to satisfy dependency injection when no abstraction is needed.
## Services
* Keep services focused on a clear responsibility.
* Avoid large catch-all services.
* Separate API access, domain logic and UI state where practical.
* Avoid leaking transport models throughout the application.
* Do not expose mutable internal state directly.
* Prefer readonly APIs for state consumers.
* Avoid hidden side effects.
* Keep service methods predictable.
* Do not use services merely to move poorly structured component code elsewhere.
## HTTP and APIs ## HTTP and APIs
* Keep API access centralized and strongly typed. * Keep API access centralized in typed data-access services, and keep DTOs separate from domain models when their responsibilities differ.
* Prefer dedicated API clients or data-access services. * The type parameter of `HttpClient.get<T>()` or `httpResource<T>()` is a compile-time assertion, not validation. Treat responses as `unknown` and validate them at the data-access boundary before they drive authorization, persistence, navigation, or rendering.
* Do not use `any` for API responses. The type parameter of `HttpClient.get<T>()` or `httpResource<T>()` is a compile-time assertion, not validation. * Configure HTTP with `provideHttpClient(withInterceptors([...]), withFetch())` and functional interceptors in new code, not `HttpClientModule` or `HTTP_INTERCEPTORS` classes. Use interceptors only for cross-cutting concerns.
* Treat all server responses as `unknown` until validated, as in the TypeScript runtime-safety rule. Validate them with a schema or parser at the data-access boundary before they drive authorization, persistence, navigation, or rendering. * Avoid duplicate requests, cache only with a clear invalidation strategy, cancel requests the user no longer needs, and handle expected error states explicitly.
* Keep DTOs separate from domain models when their responsibilities differ.
* Avoid duplicate API calls.
* Cache only when the invalidation strategy is clear.
* Avoid manual URL string construction when typed helpers or centralized endpoints are available. * Avoid manual URL string construction when typed helpers or centralized endpoints are available.
* Configure HTTP with `provideHttpClient(withInterceptors([...]), withFetch())` and functional interceptors in new code, not `HttpClientModule` or `HTTP_INTERCEPTORS` classes.
* Use interceptors only for cross-cutting concerns. ## Errors
* Do not put unrelated business logic into HTTP interceptors.
* Handle cancellation where appropriate. * Route unhandled errors to one `ErrorHandler`; `provideBrowserGlobalErrorListeners()` forwards uncaught errors and unhandled promise rejections to it. Report them without secrets or personal data, and show users a recoverable state instead of a broken view.
* Handle expected error states explicitly.
@@ -1,28 +1,17 @@
# Angular Templates and Styling # Angular Templates and Styling
Apply these rules when writing Angular templates, control flow, or component styles. Apply these rules when writing Angular templates, control flow, or component styles. Load the UI/UX rules for visual design.
## Templates ## Templates
* Keep expressions short and readable. * Keep template expressions short. Reading signals and `computed` values is correct; do not call other methods that compute or allocate from templates, and move complex conditions into `computed` state or a pure pipe.
* Reading signals and `computed` values in templates is correct. Do not call other methods that compute or allocate from templates; use `computed` or a pure pipe instead. * Use built-in control flow (`@if`, `@for`, `@switch`) in new code.
* Avoid complex conditions directly in markup.
* Prefer derived state in TypeScript over repeated template expressions.
* Use Angular control flow syntax such as `@if`, `@for` and `@switch` for new code.
* In `@for`, track a stable unique key such as `track item.id`; use `$index` only for static lists that never reorder. For legacy `*ngFor`, supply `trackBy`. * In `@for`, track a stable unique key such as `track item.id`; use `$index` only for static lists that never reorder. For legacy `*ngFor`, supply `trackBy`.
* Avoid deeply nested template structures. * Split large or deeply nested templates into focused components, and avoid unnecessary DOM elements.
* Split large templates into focused components when it improves maintainability.
* Avoid unnecessary DOM elements.
* Use semantic HTML and native elements before custom implementations; see the accessibility section of the Angular security and accessibility rule. * Use semantic HTML and native elements before custom implementations; see the accessibility section of the Angular security and accessibility rule.
* Keep user-facing text translatable with the project's i18n approach, such as `i18n` attributes and `$localize`, and format dates, numbers, and currencies with locale-aware pipes instead of hand-built strings.
## Styling ## Styling
* Keep styles scoped and predictable. * Keep styles scoped to the component and follow the project's styling strategy; avoid unnecessary global CSS and mixing styling approaches.
* Avoid unnecessary global CSS. * Prefer design tokens and shared styles over magic values. Avoid excessive specificity, `!important`, and selectors that depend on fragile DOM structure.
* Follow the project's styling strategy consistently.
* Avoid excessive specificity.
* Avoid `!important` unless there is a concrete reason.
* Prefer reusable design tokens and shared styles over duplicated magic values.
* Keep component styles focused on component concerns.
* Avoid styling based on fragile DOM structure.
* Do not mix multiple styling approaches without need.
@@ -1,44 +1,24 @@
# Angular Testing and Architecture # Angular Testing and Architecture
Apply these rules when writing Angular tests, organizing features, or changing Angular package versions. Apply these rules when writing Angular tests, organizing features, or changing Angular package versions. The TypeScript testing, coding-style, and dependency rules and the shared refactoring rule cover general test design, structure, and dependency review; this file adds Angular specifics.
## Testing ## Testing
Apply the TypeScript testing rule for general test design, and these Angular specifics.
* Use the project's test runner. New CLI projects use Vitest since Angular 21; Karma remains supported, so do not migrate runners as part of another task. * Use the project's test runner. New CLI projects use Vitest since Angular 21; Karma remains supported, so do not migrate runners as part of another task.
* In zoneless tests, configure `TestBed` with `provideZonelessChangeDetection()` and use `await fixture.whenStable()` instead of `fakeAsync` and `tick`, which require zone.js. * In zoneless tests, configure `TestBed` with `provideZonelessChangeDetection()` and use `await fixture.whenStable()` instead of `fakeAsync` and `tick`, which require zone.js.
* Set signal inputs with `fixture.componentRef.setInput()`. Test HTTP with `provideHttpClient()` plus `provideHttpClientTesting()` and `HttpTestingController`. Prefer Angular CDK component harnesses for interacting with material or CDK components. * Set signal inputs with `fixture.componentRef.setInput()`. Test HTTP with `provideHttpClient()` plus `provideHttpClientTesting()` and `HttpTestingController`. Prefer Angular CDK component harnesses for Material and CDK components.
* Test behavior, not implementation details. * Test critical user interactions through the rendered component rather than its internals.
* Prefer focused component tests.
* Test critical user interactions.
* Test services and domain logic independently where useful.
* Avoid brittle tests coupled to internal structure.
* Avoid excessive mocking.
* Mock external boundaries rather than internal implementation details.
* Keep tests deterministic.
* Avoid time-dependent tests without controlled clocks.
* Avoid network-dependent tests without proper isolation.
* Keep test setup minimal and readable.
* Update tests when refactoring changes structure but not behavior.
## Architecture ## Architecture
* Keep UI, application, domain and data-access concerns separated where practical. * Organize code by feature, and keep UI, application, domain, and data-access concerns separate where practical.
* Organize code by feature rather than by technical file type when it improves cohesion. * Keep feature public APIs small; avoid cross-feature imports without a clear contract, and keep shared code genuinely shared.
* Avoid circular dependencies.
* Avoid cross-feature imports without a clear contract.
* Keep shared code genuinely shared.
* Do not move feature-specific logic into generic shared modules.
* Avoid dumping unrelated helpers into global utility files.
* Keep public APIs of feature areas small.
* Avoid exposing internal implementation details across feature boundaries.
* Prefer local ownership of state and logic. * Prefer local ownership of state and logic.
## Code Quality and Dependencies ## Versions and dependencies
Apply the TypeScript rules for types, style, and dependency review, plus these Angular specifics. * Check the Angular version in `package.json` before using version-specific APIs.
* Treat Angular compiler, template type-checking, and lint warnings seriously; do not suppress them without a concrete reason.
* Keep all `@angular/*` packages on the same major and minor version, and upgrade them with `ng update` so migrations run. * Keep all `@angular/*` packages on the same major and minor version, and upgrade them with `ng update` so migrations run.
* Keep TypeScript inside the range the Angular version supports (angular.dev/reference/versions); Angular 22 requires TypeScript `>=6.0.0 <6.1.0`, so do not move an Angular project to TypeScript 7 before Angular supports it.
* Treat Angular compiler, template type-checking, and lint warnings seriously; do not suppress them without a concrete reason.
* Prefer Angular and browser platform capabilities before adding third-party libraries. * Prefer Angular and browser platform capabilities before adding third-party libraries.
@@ -2,7 +2,7 @@
Apply these rules when changing package dependencies, module structure, imports, or public exports. Apply these rules when changing package dependencies, module structure, imports, or public exports.
* Follow the project's existing module system and `tsconfig` consistently. For new configuration, use `module`/`moduleResolution` `nodenext` for code that Node runs directly (with explicit file extensions in relative imports) and `bundler` for bundled applications; `node`/`node10` resolution is deprecated since TypeScript 6.0. * Follow the project's existing module system and `tsconfig` consistently. For new configuration, use `module`/`moduleResolution` `nodenext` for code that Node runs directly (with explicit file extensions in relative imports) and `bundler` for bundled applications; `node`/`node10` resolution is deprecated since TypeScript 6.0. TypeScript 7.0 ships the native compiler as `tsc` and stops supporting options deprecated in 6.0, such as `target` `ES5`, `module` `AMD` or `System`, and `moduleResolution` `classic`; check that frameworks support TypeScript 7 before upgrading, because Angular 22, for example, requires TypeScript 6.0.
* Enable `verbatimModuleSyntax` in new configuration and use `import type` for type-only imports. * Enable `verbatimModuleSyntax` in new configuration and use `import type` for type-only imports.
* When code runs through Node's built-in type stripping (on by default since Node 22.18 and 23.6, stable since 24.12), enable `erasableSyntaxOnly` (TypeScript 5.8+): enums, namespaces with runtime code, parameter properties, and `import =` aliases fail there. * When code runs through Node's built-in type stripping (on by default since Node 22.18 and 23.6, stable since 24.12), enable `erasableSyntaxOnly` (TypeScript 5.8+): enums, namespaces with runtime code, parameter properties, and `import =` aliases fail there.
* Avoid mixing ESM and CommonJS without a compatibility need. `require()` of ES modules works by default from Node 20.19 and 22.12; on older runtimes, CommonJS cannot `require` an ES module. * Avoid mixing ESM and CommonJS without a compatibility need. `require()` of ES modules works by default from Node 20.19 and 22.12; on older runtimes, CommonJS cannot `require` an ES module.
@@ -11,3 +11,5 @@ Apply these rules when handling API payloads, user input, browser data, or other
* For cookie-based authentication, preserve secure cookie attributes and the application's CSRF protections. Handle session tokens as the shared web security rule defines: prefer `HttpOnly` cookies or a backend-for-frontend, keep tokens the app must hold in memory, and never store refresh tokens in `localStorage` or `sessionStorage`. * For cookie-based authentication, preserve secure cookie attributes and the application's CSRF protections. Handle session tokens as the shared web security rule defines: prefer `HttpOnly` cookies or a backend-for-frontend, keep tokens the app must hold in memory, and never store refresh tokens in `localStorage` or `sessionStorage`.
* Never expose secrets or sensitive data in output, logs, or errors. Client-side validation and route guards do not replace server-side authentication, authorization, or validation. * Never expose secrets or sensitive data in output, logs, or errors. Client-side validation and route guards do not replace server-side authentication, authorization, or validation.
* Bound input size, nesting, parsing work, and response size before processing untrusted JSON or other structured data. * Bound input size, nesting, parsing work, and response size before processing untrusted JSON or other structured data.
* Throw only `Error` objects, never strings or plain objects, and chain the original error with `{ cause }` when wrapping it. Keep `useUnknownInCatchVariables` (part of `strict`) and narrow caught values before use. Use one error model per layer, exceptions or result types, and never swallow errors silently.
* Do not use binary floating point for money or other exact decimals; use integer minor units or a decimal library. Exchange dates as ISO 8601 in UTC, and format numbers, dates, and currencies for users with `Intl`.