@tolki/ts 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -229,7 +229,7 @@ php artisan ts:publish --source="app/Enums/Status.php"
229
229
  php artisan ts:publish --source="App\Http\Resources\UserResource"
230
230
  ```
231
231
 
232
- The class can be an enum, a model, an API resource, a controller with at least one registered route, a form request, or a broadcast event. On a large project, a single-class run is much faster than a full publish. The [Vite plugin](https://tolki.abe.dev/ts/vite-plugin.html#single-file-republishing) uses it during development to republish only the file that changed.
232
+ The class can be an enum, a model, an API resource, a controller with at least one registered route, a form request, a broadcast event, or a class with a [composed type](https://tolki.abe.dev/ts/custom-types.html#composed-types). On a large project, a single-class run is much faster than a full publish. The [Vite plugin](https://tolki.abe.dev/ts/vite-plugin.html#single-file-republishing) uses it during development to republish only the file that changed.
233
233
 
234
234
  A single-class run differs from a full run in these ways:
235
235
 
@@ -343,6 +343,7 @@ Pass one `--only-*` flag to publish a single feature for one run:
343
343
  | `--only-form-requests` | Form requests |
344
344
  | `--only-broadcast-channels` | Broadcast channels |
345
345
  | `--only-broadcast-events` | Broadcast events |
346
+ | `--only-class-types` | [Composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types) |
346
347
  | `--only-functional` | Every enabled feature except model and resource interfaces |
347
348
 
348
349
  For example:
@@ -419,7 +420,7 @@ TypeScript sees these types only when your `tsconfig.json` includes the file.
419
420
 
420
421
  #### JSON Definitions File
421
422
 
422
- When `json.enabled` is `true`, the package also writes `laravel-ts-definitions.json`. It describes every published model, enum, resource, form request, and broadcast event as data, such as properties, cases, and methods, instead of TypeScript source:
423
+ When `json.enabled` is `true`, the package also writes `laravel-ts-definitions.json`. It describes every published model, enum, resource, form request, broadcast event, and [composed type](https://tolki.abe.dev/ts/custom-types.html#composed-types) as data, such as properties, cases, and methods, instead of TypeScript source:
423
424
 
424
425
  ```php
425
426
  // config/ts-publish.php
@@ -430,7 +431,7 @@ When `json.enabled` is `true`, the package also writes `laravel-ts-definitions.j
430
431
  ],
431
432
  ```
432
433
 
433
- The file has one top-level object per feature: `models`, `enums`, `resources`, `formRequests`, and `broadcastEvents`. Each object is keyed by fully-qualified class name, and each entry has a `name` field that holds the short class name:
434
+ The file has one top-level object per feature: `models`, `enums`, `resources`, `formRequests`, `broadcastEvents`, and `classTypes`. Each object is keyed by fully-qualified class name, and each entry has a `name` field that holds the short class name. A `classTypes` entry's `name` holds the composed type's name instead, such as `ChartType`, and its `extends` field lists the types that interface extends:
434
435
 
435
436
  ```json
436
437
  {
@@ -654,7 +655,7 @@ An instance or static method's value publishes as `json_encode()` writes it, whi
654
655
 
655
656
  A value that `json_encode()` can't write, such as `NAN` or a string that isn't valid UTF-8, publishes as `null`.
656
657
 
657
- An array whose integer keys don't count up from 0 in order publishes as an object keyed by those numbers, because that's how `json_encode()` writes it. `array_filter()` keeps each item's key, so it returns such an array whenever it removes an item before one it keeps. An `EnumResource` response sends the same value as a list, so `ts:publish` warns about the method. Keys that are numeric strings, such as `'01'`, are re-indexed the same way. Wrap the array in `array_values()` to publish and send a list, or use keys that aren't numeric to publish and send an object:
658
+ An array whose integer keys don't count up from 0 in order publishes as an object keyed by those numbers, because that's how `json_encode()` writes it, and an `EnumResource` response sends the same object. `array_filter()` keeps each item's key, so it returns such an array whenever it removes an item before one it keeps. Wrap the array in `array_values()` to publish and send a list:
658
659
 
659
660
  ```php
660
661
  #[TsEnumMethod]
@@ -790,6 +791,59 @@ function setStatus(status: StatusType) {} // only 'active' | 'inactive'
790
791
  function setStatusByKey(status: StatusKind) {} // only 'Active' | 'Inactive'
791
792
  ```
792
793
 
794
+ #### Reading `->value` and `->name`
795
+
796
+ Read an enum's `->value` or `->name` in an API resource, an Inertia page prop, a broadcast event, or anything else the package types, and the property publishes the enum's alias. The file imports the alias for you. Here a `PostSummaryResource` reads a `Post` model that casts `status` to the int-backed `PostStatus` enum and `visibility` to the unit enum `Visibility`:
797
+
798
+ ```php
799
+ enum PostStatus: int
800
+ {
801
+ case Draft = 0;
802
+ case Published = 1;
803
+ }
804
+
805
+ // PostSummaryResource
806
+ public function toArray(Request $request): array
807
+ {
808
+ return [
809
+ 'status' => $this->status->value,
810
+ 'status_name' => $this->status->name,
811
+ 'visibility' => $this->visibility->name,
812
+ 'published' => PostStatus::Published->value,
813
+ ];
814
+ }
815
+ ```
816
+
817
+ Each property publishes the alias that lists what PHP sends for it:
818
+
819
+ ```typescript
820
+ import type {
821
+ PostStatusKind,
822
+ PostStatusType,
823
+ VisibilityType,
824
+ } from "../../enums";
825
+
826
+ export interface PostSummaryResource {
827
+ status: PostStatusType;
828
+ status_name: PostStatusKind;
829
+ visibility: VisibilityType;
830
+ published: PostStatusType;
831
+ }
832
+ ```
833
+
834
+ A backed enum's `->value` publishes its `{Name}Type`, and its `->name` publishes its `{Name}Kind`. A unit enum's `->name` publishes its `{Name}Type`, because its values are its case names.
835
+
836
+ `PostStatus::Published->value` and `PostStatus::from($value)->value` publish `PostStatusType` too. After `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
837
+
838
+ The property uses the alias only when `ts:publish` publishes the enum, and when no case's `#[TsCase]` changes what the alias lists. For a `{Name}Type` that's the case's `value`, and for a `{Name}Kind` its `name`. Otherwise the property publishes the literal union of what PHP sends.
839
+
840
+ An enum the [filters](#filtering--excluding-enums) leave out publishes the literal union too, and so does every enum while `enums.enabled` is off. For the `Status` enum in the [`#[TsCase]`](#tscase) example, `->value` publishes `1 | 0` and `->name` publishes `'Active' | 'Inactive'`. An int-backed enum with a case outside JavaScript's safe integer range (±2⁵³−1) publishes `number` for `->value`.
841
+
842
+ In two cases the alias can't be imported, so the property publishes the literal union:
843
+
844
+ - A helper method's array that a resource uses as a value. A spread of the same helper keeps the aliases, as [Methods Declared as a Bare `array`](https://tolki.abe.dev/ts/api-resources.html#methods-declared-as-a-bare-array) shows.
845
+ - A [route file](https://tolki.abe.dev/ts/routing.html), the [Inertia shared data](https://tolki.abe.dev/ts/inertia.html) file or a [model metadata](https://tolki.abe.dev/ts/model-metadata.html) companion that reads the `->name` of two enums with the same class name, such as `App\Enums\Status` and `App\Crm\Enums\Status`. These files can't import two names that clash, so each read publishes its case names.
846
+
793
847
  ### Metadata & the `defineEnum()` Wrapper
794
848
 
795
849
  With `enums.metadata_enabled` on, every enum has a `_cases` list, plus `_methods` and `_static` lists when it publishes instance or static methods. You don't read these lists yourself. `defineEnum()` and the standalone `from`, `tryFrom` and `cases` functions use them to build a PHP-like instance from a case value:
@@ -975,7 +1029,7 @@ The `ts:publish` command publishes each model as follows:
975
1029
 
976
1030
  - **One file per model**: `App\Models\User` is written to `app/models/user.ts`, following the model's namespace. Each namespace directory also gets an `index.ts` barrel that re-exports its files (`export * from './user'`), the same as [enums](https://tolki.abe.dev/ts/enums.html#how-enums-are-generated).
977
1031
  - **Split interfaces**: columns, accessors and relations go into separate interfaces by default. See [Model Templates](#model-templates).
978
- - **Column types**: a column's type comes from the first source that applies. In order, those are a [`#[TsCasts]`](#tscasts) entry, an accessor with the column's name, the model's cast in `casts()` or `$casts`, and the database column type. A custom cast class can set its own type with [`#[TsType]`](#tstype). When the result is still vague, such as `unknown[]`, a class-level `@property` tag refines it. The [Type Mapping Reference](#type-mapping-reference) lists the default types.
1032
+ - **Column types**: a column's type comes from the first source that applies. In order, those are a [`#[TsCasts]`](#tscasts) entry, an accessor with the column's name, the model's cast in `casts()` or `$casts`, and the database column type. A custom cast class can set its own type with [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html#model-attributes-and-casts). When the result is still vague, such as `unknown[]`, a class-level `@property` tag refines it. The [Type Mapping Reference](#type-mapping-reference) lists the default types.
979
1033
  - **Accessors**: new-style `Attribute` accessors and old-style `get{Name}Attribute()` methods that aren't columns publish as mutators, typed from their return types, their docblocks or what their getters return.
980
1034
  - **Relations**: each relation publishes, plus a `_count` and an `_exists` property for it.
981
1035
  - **Metadata companions**: an opt-in feature writes a runtime `{model}_meta.ts` file beside the interface. See [Model Metadata](https://tolki.abe.dev/ts/model-metadata.html).
@@ -1255,11 +1309,11 @@ A relation's `_count` and `_exists` properties follow the same rule. When a colu
1255
1309
 
1256
1310
  All attributes live in the `AbeTwoThree\LaravelTsPublish\Attributes` namespace.
1257
1311
 
1258
- | Attribute | Target | Description |
1259
- | -------------- | --------------------------------------------------- | -------------------------------------------------------------------- |
1260
- | `#[TsCasts]` | `casts()` method, `$casts` property, or model class | Override or add TypeScript types for columns, mutators or relations. |
1261
- | `#[TsType]` | Custom cast class | Set the TypeScript type used wherever this cast class is applied. |
1262
- | `#[TsExclude]` | Model class, accessor method, or relation method | Exclude a whole model, or one accessor or relation. |
1312
+ | Attribute | Target | Description |
1313
+ | -------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------- |
1314
+ | `#[TsCasts]` | `casts()` method, `$casts` property, or model class | Override or add TypeScript types for columns, mutators or relations. |
1315
+ | `#[TsType]` | Any class, such as a custom cast class | Set the TypeScript type of every value of the class, or of every column that uses the cast. |
1316
+ | `#[TsExclude]` | Model class, accessor method, or relation method | Exclude a whole model, or one accessor or relation. |
1263
1317
 
1264
1318
  #### `#[TsCasts]`
1265
1319
 
@@ -1304,39 +1358,7 @@ Put `#[TsCasts]` on `casts()` or `$casts`, so the TypeScript type sits next to t
1304
1358
 
1305
1359
  #### `#[TsType]`
1306
1360
 
1307
- For a custom cast class you use on several models, put `#[TsType]` on the cast class once, instead of repeating `#[TsCasts]` everywhere you use it:
1308
-
1309
- ```php
1310
- use AbeTwoThree\LaravelTsPublish\Attributes\TsType;
1311
-
1312
- #[TsType(['type' => 'ProductDimensions', 'import' => '@js/types/product'])]
1313
- class ProductDimensionsCast implements CastsAttributes
1314
- {
1315
- public function get($model, string $key, $value, array $attributes) { /* ... */ }
1316
- }
1317
-
1318
- class Product extends Model
1319
- {
1320
- public function casts(): array
1321
- {
1322
- return ['dimensions' => ProductDimensionsCast::class];
1323
- }
1324
- }
1325
- ```
1326
-
1327
- Every column that uses the cast publishes with that type:
1328
-
1329
- ```typescript
1330
- import type { ProductDimensions } from "@js/types/product";
1331
-
1332
- export interface Product {
1333
- dimensions: ProductDimensions;
1334
- }
1335
- ```
1336
-
1337
- `#[TsType]` also takes a plain string, such as `#[TsType('{width: number, height: number}')]`, when the type needs no import. Without `#[TsType]`, a custom cast publishes the return type of its `get()` method. A cast class that implements `SerializesCastableAttributes`, including one a `Castable` value object names, publishes the return type of its `serialize()` method instead, because that's what Laravel sends when it converts the model to JSON.
1338
-
1339
- When `get()`'s native type is missing or vague, such as a bare `array`, the `@return` docblock sets the type, so `@return list<LegDto>` publishes a list of `LegDto`'s public properties, the shape `json_encode()` writes. A `@return` that names a model, such as `list<User>`, or another class that doesn't publish as an inline shape keeps `unknown[]`. A `get()` that declares neither publishes `unknown`.
1361
+ Put `#[TsType]` on a custom cast class, or on any class a column holds, to set the column's type. [Custom Types](https://tolki.abe.dev/ts/custom-types.html) describes the attribute.
1340
1362
 
1341
1363
  ### Laravel 13 Model Attributes
1342
1364
 
@@ -1557,6 +1579,12 @@ export interface ProjectMutators {
1557
1579
 
1558
1580
  PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too.
1559
1581
 
1582
+ #### Custom Cast Classes
1583
+
1584
+ A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes the return type of its `get()` method. A cast class that implements `SerializesCastableAttributes`, including one a `Castable` value object names, publishes the return type of its `serialize()` method instead, because that's what Laravel sends when it converts the model to JSON.
1585
+
1586
+ When `get()`'s native type is missing or vague, such as a bare `array`, the `@return` docblock sets the type, so `@return list<LegDto>` publishes a list of `LegDto`'s public properties, the shape `json_encode()` writes. A `@return` that names a model, such as `list<User>`, or another class that doesn't publish as an inline shape keeps `unknown[]`. A `get()` that declares neither publishes `unknown`.
1587
+
1560
1588
  #### Typing Castable-With-Arguments Casts
1561
1589
 
1562
1590
  Laravel's built-in `Castable` classes carry their configuration after a colon in the cast string. `AsEnumCollection::of(DayOfWeek::class)`, `AsCollection::of(...)` and `AsCollection::using(...)` all build a `"ClassName:arg1,arg2"` cast string. The package types these with no extra configuration:
@@ -1661,7 +1689,7 @@ final readonly class ShippingOptions implements Arrayable
1661
1689
  }
1662
1690
  ```
1663
1691
 
1664
- An accessor or cast that returns this DTO publishes as `{ carrier: string; insured: boolean; trackingUrl: string | null }`. Nullable properties keep their `| null`. Private, protected and static properties are left out, because `(array) $this` doesn't include them. A property typed as a class or an enum, such as a model, publishes as `unknown`, because the inline shape can't import it.
1692
+ An accessor or cast that returns this DTO publishes as `{ carrier: string; insured: boolean; trackingUrl: string | null }`. Nullable properties keep their `| null`. Private, protected and static properties are left out, because `(array) $this` doesn't include them. A property typed as a class or an enum, such as a model, publishes as `unknown`, because the inline shape can't import it. A property whose class has or inherits a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes that type, with its import.
1665
1693
 
1666
1694
  Optional is separate from nullable. A property that is neither promoted nor given a default value publishes as an optional key. Add `public string $summary;` to the class body above, assigned in the constructor, and it publishes as `summary?: string`. PHP leaves an unassigned typed property out of `(array) $this`, and the package can't tell whether the constructor always assigns it. To keep the key required, promote the property, or give it a default value on a DTO that isn't `readonly`. A `@return array{...}` docblock on `toArray()` always wins, so add one when the properties don't tell the whole story.
1667
1695
 
@@ -1779,7 +1807,7 @@ To change how a type publishes everywhere, add it to `custom_ts_mappings`. Keys
1779
1807
 
1780
1808
  To see which entry a cast, a column or a date follows, read [`custom_ts_mappings`](https://tolki.abe.dev/ts/configuration-reference.html#custom-ts-mappings) in the Configuration Reference.
1781
1809
 
1782
- To change one property instead of every column of a type, use [`#[TsCasts]`](#tscasts) or [`#[TsType]`](#tstype).
1810
+ To change one property instead of every column of a type, use [`#[TsCasts]`](#tscasts) or [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html).
1783
1811
 
1784
1812
  ### Type Mapping Reference
1785
1813
 
@@ -2033,6 +2061,46 @@ Point `model_metadata.provider_class` at your class. The published config ships
2033
2061
 
2034
2062
  Prefer a precise `@return array{...}` shape. PHPStan or Psalm checks the contract, and the package publishes the same shape. The published config names no classes of its own. Every `*_class` key, `provider_class` included, is a commented line that shows what you can swap, and the default applies in code.
2035
2063
 
2064
+ Your provider can inherit `provide()` from a base class, or take it from a trait. The package reads it as PHP runs it on the provider that `provider_class` names. `$this->` and `static::` reach that provider, and `self::` reaches the class that declares `provide()`, which for a trait is the class that uses it:
2065
+
2066
+ ```php
2067
+ abstract class BaseModelMetadataProvider implements ModelMetadataProvider
2068
+ {
2069
+ public function provide(Model $model): array
2070
+ {
2071
+ return [
2072
+ 'morphClass' => (string) $model->getMorphClass(),
2073
+ 'channel' => $this->channel($model),
2074
+ ];
2075
+ }
2076
+
2077
+ protected function channel(Model $model): ?string
2078
+ {
2079
+ return null;
2080
+ }
2081
+ }
2082
+
2083
+ final class AppModelMetadataProvider extends BaseModelMetadataProvider
2084
+ {
2085
+ protected function channel(Model $model): string
2086
+ {
2087
+ return $model->getTable().'.updates';
2088
+ }
2089
+ }
2090
+ ```
2091
+
2092
+ With `provider_class` set to `AppModelMetadataProvider`, `channel` publishes the override's `string`, not the base class's `string | null`:
2093
+
2094
+ ```typescript
2095
+ export const UserModelMetadata = {
2096
+ morphClass: "App\\Models\\User",
2097
+ channel: "users.updates",
2098
+ } as const satisfies {
2099
+ morphClass: string;
2100
+ channel: string;
2101
+ };
2102
+ ```
2103
+
2036
2104
  ### How Each Key Is Typed
2037
2105
 
2038
2106
  Each returned key's TypeScript type comes from the first of these that applies:
@@ -2043,8 +2111,9 @@ Each returned key's TypeScript type comes from the first of these that applies:
2043
2111
  - Scalars, casts such as `(string) …`, and nested inline arrays
2044
2112
  - Calls on `$model` whose Laravel signature or docblock declares a return type, such as `getTable()`, `getKeyName()`, `getRouteKeyName()` and `getMorphClass()`, which all publish as `string`
2045
2113
  - Enum values, including a case written inline such as `'status' => Status::Active`, which import their `{Name}Type` alias from the generated enums, the same as a `#[TsCasts]` import would
2114
+ - An `instanceof` test on `$model`, which narrows it where the test holds, and relation calls that the query answers, as in `$model instanceof Post ? $model->comments()->count() : null`, which publishes `number | null`
2046
2115
 
2047
- When the body's type for a key still contains `unknown`, the package ignores it, and the key needs a docblock or `#[TsCasts]` type. A helper with no declared return type, such as `private function tableFor($model)`, is that case.
2116
+ When the body's type for a key still contains `unknown`, the package ignores it, and the key needs a docblock or `#[TsCasts]` type. A helper with no declared return type, such as `private function tableFor($model)`, is that case. Inside a ternary or another union, a value the body can't type is left out instead, as in an API resource. See [Values Left Out of a Union](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union).
2048
2117
 
2049
2118
  Marking a key optional decides whether the payload has to return it, not how the key is written once it's returned. The `satisfies` type lists exactly the keys the payload returned, each one required.
2050
2119
 
@@ -2316,6 +2385,8 @@ For `whenNotNull()` and `whenNull()`, the second argument is that default value,
2316
2385
  'discount' => $this->whenNotNull($this->discount_percent, 0), // discount: number
2317
2386
  ```
2318
2387
 
2388
+ A closure or a first-class callable is never `null`, so `whenNotNull()` always includes the key and sends what the call returns, `null` included. Over a nullable `rating` column, `'rating' => $this->whenNotNull(fn () => $this->rating)` publishes `rating: string | null`.
2389
+
2319
2390
  A default of the value's own type makes the property required without widening it. A default of another type, such as a string fallback for a number column, publishes a union of both.
2320
2391
 
2321
2392
  An explicit `null` counts as a default, because Laravel checks whether you passed the argument, not what it holds. So `$this->whenLoaded('user', fn ($user) => $user, null)` is required, and it publishes `User | null` instead of `User`.
@@ -2357,11 +2428,11 @@ When you pass a closure as the value, its first parameter holds whatever Laravel
2357
2428
  | `whenExistsLoaded()` | The relation's `{relation}_exists` flag, a `boolean` |
2358
2429
  | `whenCounted()`, and `whenAggregated()` with the `count` function | The count, a `number` |
2359
2430
  | `whenAggregated()` with any other function | The aggregate, never `null` |
2360
- | `transform()` | The value you pass as its first argument |
2361
- | `when()`, `unless()` | No value, since Laravel passes none. A closure that requires a parameter throws `ArgumentCountError` whenever Laravel calls it, and `ts:publish` warns about it. |
2431
+ | `transform()` | The value you pass as its first argument, without `null`, since Laravel calls the closure only for a filled value |
2432
+ | `when()`, `unless()`, `whenNotNull()` | No value, since Laravel passes none. A closure that requires a parameter throws `ArgumentCountError` whenever Laravel calls it, and `ts:publish` warns about it. |
2362
2433
  | `whenAppended()` | No value, since Laravel passes none |
2363
2434
 
2364
- When Laravel passes no value, a parameter with a default holds that default's type.
2435
+ When Laravel passes no value, a parameter with a default holds that default's type. A default that builds a model holds that model, so `fn ($post = new Post) => $post->author?->name` publishes `string | null`.
2365
2436
 
2366
2437
  The closure's return type becomes the property's type:
2367
2438
 
@@ -2370,7 +2441,7 @@ The closure's return type becomes the property's type:
2370
2441
  'has_comments' => $this->whenExistsLoaded('comments', fn ($exists) => $exists), // has_comments?: boolean
2371
2442
  ```
2372
2443
 
2373
- Here `author` is a relation that can't load `null`. When a relation is loaded as `null`, Laravel returns `null` without calling the closure, so a relation that can load `null` publishes `author_name?: string | null`. A `whenAggregated()` closure works the same way when its function is a string literal other than `'count'`, because SQL returns `NULL` for that aggregate over no rows. So `fn ($max) => ['max' => $max]` publishes `{ max: number } | null`, unless an accessor or `@property` on your model types the attribute without `null`. See [Nullable Relations](#nullable-relations) for which relations can load `null`.
2444
+ Here `author` is a relation that can't load `null`. When a relation is loaded as `null`, Laravel returns `null` without calling the closure, so a relation that can load `null` publishes `author_name?: string | null`. A `whenAggregated()` closure works the same way when its function is a string literal other than `'count'`, because SQL returns `NULL` for that aggregate over no rows. So `fn ($max) => ['max' => $max]` publishes `{ max: number } | null`, unless an accessor or `@property` on your model types the attribute without `null`. A closure that hands the relation to a resource's `collection()` adds `| null` only for a to-one relation that can load `null`. See [Nullable Relations](#nullable-relations) for which relations can load `null`.
2374
2445
 
2375
2446
  ##### `whenHas()`, `whenAppended()`, and `whenExistsLoaded()` Type From the Value You Pass
2376
2447
 
@@ -2712,6 +2783,8 @@ $this->merge(function () {
2712
2783
 
2713
2784
  The closure publishes `user_name?: string` and `user_email?: string`.
2714
2785
 
2786
+ A closure can also build its array in a variable and return it. The merge then publishes the keys that the variable's writes set, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes. If an `unset()` that the package can't follow may remove one of its keys, the merge adds none of them. A variable the closure assigns is its own, even when the method has one with the same name.
2787
+
2715
2788
  A merge can also take the resource's own model, `$this->resource`, or a call to one of the resource's methods, such as `$this->labelFields()`, passed as it is or returned from a closure:
2716
2789
 
2717
2790
  ```php
@@ -2745,17 +2818,76 @@ A closure or an arrow function in value position is typed from what it returns:
2745
2818
 
2746
2819
  This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`.
2747
2820
 
2748
- A first-class callable, such as `$this->label(...)` or `UserResource::make(...)`, creates a closure. Where Laravel calls the value, as `when()`, `whenLoaded()` and the other conditional methods do, it publishes what the call returns:
2821
+ A closure that builds an array in a variable and returns it publishes the keys its writes set, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes:
2822
+
2823
+ ```php
2824
+ 'summary' => $this->when($this->published_at !== null, function () {
2825
+ $summary = ['id' => $this->id];
2826
+
2827
+ if ($this->is_pinned) {
2828
+ $summary['flag'] = 'pinned';
2829
+ } else {
2830
+ $summary['flag'] = 0;
2831
+ }
2832
+
2833
+ return $summary;
2834
+ }),
2835
+ ```
2836
+
2837
+ The property publishes `summary?: { id: number; flag: string | number }`.
2838
+
2839
+ A first-class callable, such as `$this->label(...)` or `UserResource::make(...)`, creates a closure. Where Laravel calls the value, as `when()`, `whenLoaded()`, `mergeWhen()` and the other conditional methods do, it publishes what the call returns, whether you pass the callable directly or through a local:
2749
2840
 
2750
2841
  ```php
2751
- 'label' => $this->when($request->has('label'), $this->label(...)), // label?: string
2752
- 'supervisor' => $this->whenLoaded('supervisor', UserResource::make(...)), // supervisor?: UserResource | null
2753
- 'length' => strlen(...), // length: Record<string, never>
2842
+ public function toArray(Request $request): array
2843
+ {
2844
+ $label = $this->label(...);
2845
+
2846
+ return [
2847
+ 'label' => $this->when($request->has('label'), $label), // label?: string
2848
+ 'supervisor' => $this->whenLoaded('supervisor', UserResource::make(...)), // supervisor?: UserResource | null
2849
+ 'length' => strlen(...), // length: Record<string, never>
2850
+ $this->mergeWhen($request->has('stats'), $this->statFields(...)), // views?: number
2851
+ ];
2852
+ }
2853
+
2854
+ /** @return array{views: int} */
2855
+ public function statFields(): array
2856
+ {
2857
+ return ['views' => 1];
2858
+ }
2754
2859
  ```
2755
2860
 
2756
2861
  As a plain value, nothing calls it, and Laravel sends the `Closure` as `{}`, so a first-class callable there, like `length` above, publishes `Record<string, never>`. `ts:publish` warns about such a callable and names its line. Call the function instead, as in `'length' => strlen($this->name)`.
2757
2862
 
2758
- `ts:publish` doesn't analyze a class again while the [generation cache](https://tolki.abe.dev/ts/generating-cache.html) holds it, so a warning may not repeat on the next run. Run `php artisan ts:publish --fresh` to list every warning.
2863
+ #### Values Left Out of a Union
2864
+
2865
+ When the package can't type one value of a union, it leaves that value out and publishes the others. Here `opaqueTags()` and `opaqueNote()` declare no return type and return something the package can't type:
2866
+
2867
+ ```php
2868
+ 'tags' => $this->is_published ? $this->opaqueTags() : [], // tags: never[]
2869
+ 'note' => $this->is_published ? $this->opaqueNote() : null, // note: null
2870
+ ```
2871
+
2872
+ The same happens to a `??`, a `match`, a write to a closure's or helper's parameter inside a block, and a key that one branch of a returned array writes, where the writes join, as [Local Variables and Narrowing](#local-variables-and-narrowing) describes. Some unions widen to `unknown` instead, such as a method you read as a value when one of its returns can't be typed.
2873
+
2874
+ When what's left is only `null`, an empty array, or both, the published type claims the value is always that. `ts:publish` prints a warning after its summary, naming the class, the line, and the value it left out:
2875
+
2876
+ ```text
2877
+ App\Http\Resources\PostResource: The value on line 24 publishes `never[]`, an array that is always empty, because `$this->opaqueTags()` could not be typed and was left out of its union. Give what it reads a return type or a `@return` docblock.
2878
+ ```
2879
+
2880
+ For a value left as `null`, the message reads "publishes `null`, as if it were always null", and for both, "publishes `null | never[]`, as if it were always null or an empty array".
2881
+
2882
+ A ternary or a `??` that leaves out a value beside a typed one raises no warning. A value left out where a parameter's writes, a returned array's branches, a merge's two sides or a spread helper's returns join raises one, because the published type may not cover everything Laravel sends:
2883
+
2884
+ ```text
2885
+ App\Http\Resources\PostResource: The value on line 31 leaves out `$this->opaqueTitle()`, which could not be typed, so its published type may not admit every value it sends. Give what it reads a return type or a `@return` docblock.
2886
+ ```
2887
+
2888
+ Give the method a return type or a `@return` docblock, and its value joins the union again. An inline [`@var`](#typing-a-variable-with-var) that types the variable also removes the warning. `--quiet` hides every warning.
2889
+
2890
+ `ts:publish` doesn't analyze a class again while the [generation cache](https://tolki.abe.dev/ts/generating-cache.html) holds it. A class the cache serves prints none of these warnings, nor the first-class callable warning above, so run `php artisan ts:publish --fresh` to see every one.
2759
2891
 
2760
2892
  ### Method Calls, Variables, and Collections
2761
2893
 
@@ -2862,20 +2994,65 @@ A model that no database row backs yet has no key, so its `getKey()` adds `| nul
2862
2994
 
2863
2995
  A call that returns the same model, such as `(new Post)->fill([...])`, keeps the `| null`. A helper's `Post $post` parameter adds it only where the call passes a model no row backs yet. The package doesn't follow `save()`, so a model you save after `new` still publishes `number | null`. On a model whose `$primaryKey` is `null`, `getKey()` publishes `null`.
2864
2996
 
2997
+ A model you build with `new` and no attributes holds no columns either, so Laravel sends `null` for each one, and a column read on it adds `| null`. `(new Post)->title` publishes `string | null`. A column you set keeps its type, whether you pass it to the constructor, `fill()` it, or write it, as in `$post->title = 'Draft'`. So does every column of a model from `replicate()`, `firstOrNew()` or a factory's `make()`. A relation, an accessor, and a column your model's `$attributes` gives a default publish their types as usual.
2998
+
2865
2999
  On an abstract model, `getKey()` publishes the key type the class declares, through `$keyType`, `HasUuids`, `HasUlids` or Laravel 13's `#[Table]`, joined with the key type of each published model that extends it. So a base whose subclasses key by integer and by UUID publishes `number | string`. When the abstract model works its key out in code, such as in an overridden `getKeyType()`, `getKey()` publishes `unknown`.
2866
3000
 
2867
3001
  `getAuthIdentifier()` on an authenticatable model publishes the type of the column the model identifies users by. That's the key type, or the type of the column a literal `getAuthIdentifierName()` returns, so a model whose `getAuthIdentifierName()` returns `'email'` publishes `string`. A model no row backs yet adds `| null`, and a model that overrides `getAuthIdentifier()` publishes the return type it declares.
2868
3002
 
2869
3003
  A method that returns a plain PHP `DateTime` or `DateTimeImmutable` publishes `{ date: string; timezone_type: number; timezone: string }`, the object `json_encode()` writes for it. A Carbon date publishes `string`, or `Date` under `timestamps_as_date`, and so do the `now()` and `today()` helpers, which return one. A `DateTimeInterface` can hold either kind, so it publishes the Carbon date's type or that object, and a `CarbonPeriod` publishes a list of the Carbon date's type. A `CarbonInterval` publishes the `DateInterval` fields `json_encode()` writes for it, such as `y`, `m`, `d` and `days`. `str($value)` publishes `string`, and `str()` with no argument publishes `Record<string, never>`. `url($path)` publishes `string` when the path can't be `null`, and `unknown` when it can or has no type.
2870
3004
 
2871
- A value built in place publishes what `json_encode()` writes for it as well, so `new DateTime()` publishes that date object and `new RuntimeException('x')` publishes `Record<string, never>`. `new Collection($items)` publishes as `collect($items)` does. These values stay `unknown` when built in place:
3005
+ A value built in place publishes what `json_encode()` writes for it as well, so `new DateTime()` publishes that date object and `new RuntimeException('x')` publishes `Record<string, never>`. `new Collection($items)` publishes as `collect($items)` does. `new stdClass`, and a method declared to return `stdClass`, publish `Record<string, unknown>`, because a `stdClass` can gain properties at run time.
3006
+
3007
+ These values stay `unknown` when built in place:
2872
3008
 
2873
3009
  - An `Arrayable` or a `Responsable`
2874
3010
  - An Inertia `ProvidesInertiaProperty` class
2875
3011
  - A model
2876
- - A class with no public property and no `__toString()`, such as `stdClass`
3012
+ - A class with no public property and no `__toString()`
3013
+
3014
+ Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts), or give the class a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html). A `new` of a class that has or inherits one publishes that type, unless the class is a model.
3015
+
3016
+ `array_values()` keeps the element type and publishes a list. An `(object)` cast publishes the object `json_encode()` writes: a shape keeps its keys, a list becomes a `Record` keyed by its indexes, and `(object) []` publishes `Record<string, never>`. An `(array)` cast of an array keeps the array's type:
3017
+
3018
+ ```php
3019
+ public function toArray(Request $request): array
3020
+ {
3021
+ return [
3022
+ 'tags' => array_values(array_filter($this->tags())),
3023
+ 'count_list' => array_values($this->tagCounts()),
3024
+ 'tag_counts' => (object) $this->tagCounts(),
3025
+ 'tag_object' => (object) $this->tags(),
3026
+ 'size' => (object) ['width' => 640, 'label' => 'large'],
3027
+ 'counts' => (array) $this->tagCounts(),
3028
+ ];
3029
+ }
2877
3030
 
2878
- Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
3031
+ /** @return list<string> */
3032
+ private function tags(): array
3033
+ {
3034
+ return explode(',', $this->title);
3035
+ }
3036
+
3037
+ /** @return array<string, int> */
3038
+ private function tagCounts(): array
3039
+ {
3040
+ return array_count_values($this->tags());
3041
+ }
3042
+ ```
3043
+
3044
+ Each key publishes the list or object PHP sends:
3045
+
3046
+ ```typescript
3047
+ export interface PostTagsResource {
3048
+ tags: string[];
3049
+ count_list: number[];
3050
+ tag_counts: Record<string, number>;
3051
+ tag_object: Record<string, string>;
3052
+ size: { width: number; label: string };
3053
+ counts: Record<string, number>;
3054
+ }
3055
+ ```
2879
3056
 
2880
3057
  A method that returns the base `Model` class, `Illuminate\Foundation\Auth\User`, an abstract model, or a model that isn't published, such as one in `models.excluded`, publishes `unknown`, because no published file has a type for it. Declare the concrete model as the return type, such as `: Order`, to type the value.
2881
3058
 
@@ -2921,12 +3098,13 @@ Outside a resource, such as in an Inertia page prop, `tiers` publishes `{ "1": s
2921
3098
 
2922
3099
  A `?array` declaration keeps its `null`, so the method publishes the shape `| null`. An `array|false` declaration keeps its `false` the same way.
2923
3100
 
2924
- What the body reads from the method's parameters is typed too, whether you use its result as a value or spread it. Each parameter holds its declared type, from the signature, or from a `@param` tag when the signature's type is missing or vague, such as `array`. A parameter with no type, or only `mixed`, holds what each call passes. A closure you pass is the exception: in `$this->hold(fn () => 5)`, the parameter holds `unknown`, because a resource sends a closure as `{}`. A first-class callable that Laravel calls gets the value Laravel calls it with, as in `whenLoaded()`:
3101
+ What the body reads from the method's parameters is typed too, whether you use its result as a value or spread it. Each parameter holds its declared type, from the signature, or from a `@param` tag when the signature's type is missing or vague, such as `array`. A parameter with no type, or only `mixed`, holds what each call passes, and a collection you pass keeps its model, so a read such as `$comments->first()?->content` is typed. A closure you pass is the exception: in `$this->hold(fn () => 5)`, the parameter holds `unknown`, because a resource sends a closure as `{}`. A first-class callable that Laravel calls gets the value Laravel calls it with, as in `whenLoaded()`:
2925
3102
 
2926
3103
  ```php
2927
3104
  'card' => $this->card($this->resource), // card: { id: number; title: string }
2928
3105
  'author_card' => $this->authorCard($this->author), // author_card: { name: string }
2929
3106
  'loaded_card' => $this->whenLoaded('author', $this->authorCard(...)), // loaded_card?: { name: string }
3107
+ 'first_comment' => $this->firstContent($this->comments), // first_comment: { first: string | null }
2930
3108
 
2931
3109
  private function card(Post $post): array
2932
3110
  {
@@ -2937,6 +3115,11 @@ private function authorCard($author): array
2937
3115
  {
2938
3116
  return ['name' => $author->name];
2939
3117
  }
3118
+
3119
+ private function firstContent($comments): array
3120
+ {
3121
+ return ['first' => $comments->first()?->content];
3122
+ }
2940
3123
  ```
2941
3124
 
2942
3125
  When the method can return something other than an array literal, apart from a `null`, boolean, string, or number literal its declaration allows, the package reads each `return` as a value instead, as [Method Return Types](#method-return-types) describes. So a method that returns a collection pipeline publishes its list:
@@ -2950,9 +3133,79 @@ private function contents(): array
2950
3133
  }
2951
3134
  ```
2952
3135
 
3136
+ The pipeline can also start at a relation of a model parameter, at a query's `get()`, or at a local holding either:
3137
+
3138
+ ```php
3139
+ final class CommentRowsService
3140
+ {
3141
+ public function forPost(Post $post): array
3142
+ {
3143
+ return $post->comments->map(fn ($comment) => ['id' => $comment->id])->values()->all();
3144
+ }
3145
+
3146
+ public function unflagged(): array
3147
+ {
3148
+ $rows = Comment::query()->where('is_flagged', false)->get();
3149
+
3150
+ return $rows->map(fn ($comment) => ['id' => $comment->id])->all();
3151
+ }
3152
+ }
3153
+
3154
+ // in toArray():
3155
+ 'post_rows' => resolve(CommentRowsService::class)->forPost($this->resource), // post_rows: { id: number }[]
3156
+ 'unflagged_rows' => resolve(CommentRowsService::class)->unflagged(), // unflagged_rows: { id: number }[]
3157
+ ```
3158
+
3159
+ A method that builds its array in a variable and returns it publishes the keys its writes set. Beside a `return` of another array, each `return` is one shape of a union:
3160
+
3161
+ ```php
3162
+ 'summary' => $this->summary($request), // summary: { id: number } | { id: number; title: string }
3163
+
3164
+ private function summary(Request $request): array
3165
+ {
3166
+ if ($request->boolean('short')) {
3167
+ return ['id' => $this->id];
3168
+ }
3169
+
3170
+ $data = ['id' => $this->id];
3171
+ $data['title'] = $this->title;
3172
+
3173
+ return $data;
3174
+ }
3175
+ ```
3176
+
2953
3177
  If one `return` can't be typed, or the method yields, the property publishes `unknown`.
2954
3178
 
2955
- When you use the method's result as a value, a value in the array that is an enum or a model publishes `unknown`, because a method body can't supply the import it needs. The rest of the shape keeps its types. Spreading the same method keeps an enum's type. To type that value, build the array in `toArray()` itself, or override the property with [`#[TsCasts]`](#overriding-property-types-with-tscasts) and a type your frontend exports, as in `['type' => 'StatusPayload', 'import' => '@/types/payloads']`. An entry imports only a type it names whole, so a type named inside a shape you write in the entry isn't imported.
3179
+ When you use the method's result as a value, a value in the array that is an enum or a model publishes `unknown`, because a method body can't supply the import it needs. The rest of the shape keeps its types, and an enum's `->value` or `->name` publishes the literal union of its values or names, as [Reading `->value` and `->name`](https://tolki.abe.dev/ts/enums.html#reading-value-and-name) describes. Spreading the same method keeps an enum's type. To type that value, build the array in `toArray()` itself, or override the property with [`#[TsCasts]`](#overriding-property-types-with-tscasts) and a type your frontend exports, as in `['type' => 'StatusPayload', 'import' => '@/types/payloads']`. An entry imports only a type it names whole, so a type named inside a shape you write in the entry isn't imported.
3180
+
3181
+ Here a `Post` casts `status` to the int-backed `PostStatus` enum, whose cases are `Draft = 0` and `Published = 1`. The resource uses `statusLabel()` as a value, then spreads it:
3182
+
3183
+ ```php
3184
+ public function toArray(Request $request): array
3185
+ {
3186
+ return [
3187
+ 'label' => $this->statusLabel($this->status),
3188
+ ...$this->statusLabel($this->status),
3189
+ ];
3190
+ }
3191
+
3192
+ private function statusLabel(PostStatus $status): array
3193
+ {
3194
+ return ['name' => $status->name, 'value' => $status->value];
3195
+ }
3196
+ ```
3197
+
3198
+ `label` publishes the literal unions, and the spread keys publish the enum's aliases:
3199
+
3200
+ ```typescript
3201
+ import type { PostStatusKind, PostStatusType } from "../../enums";
3202
+
3203
+ export interface PostLabelResource {
3204
+ label: { name: "Draft" | "Published"; value: 0 | 1 };
3205
+ name: PostStatusKind;
3206
+ value: PostStatusType;
3207
+ }
3208
+ ```
2956
3209
 
2957
3210
  A model's own `toArray()`, called as a value, publishes `Record<string, unknown>`, because the relations it includes depend on what's loaded at runtime. A relation's collection, as in `$this->comments->toArray()`, publishes `Record<string, unknown>[]`. To publish the model's keys, spread it instead, as [Model `toArray()` Spread](#model-toarray-spread) shows.
2958
3211
 
@@ -3010,7 +3263,7 @@ Registering, removing, or re-pointing a macro makes the next `ts:publish` rebuil
3010
3263
 
3011
3264
  #### Local Variables and Narrowing
3012
3265
 
3013
- A variable you assign once keeps the type of its value, so you don't need to inline the expression. Assign it in a statement at the top level of the method or of a closure body:
3266
+ A variable keeps the type of the value you assign it, so you don't need to inline the expression:
3014
3267
 
3015
3268
  ```php
3016
3269
  public function toArray(Request $request): array
@@ -3023,6 +3276,20 @@ public function toArray(Request $request): array
3023
3276
  }
3024
3277
  ```
3025
3278
 
3279
+ A variable assigned inside an `if`, a loop, or a `try` block keeps that type for the reads after it in the same block:
3280
+
3281
+ ```php
3282
+ 'title_or_count' => $this->when($request->has('title'), function () {
3283
+ if ($this->is_pinned) {
3284
+ $title = $this->title;
3285
+
3286
+ return $title;
3287
+ }
3288
+
3289
+ return 7;
3290
+ }), // title_or_count?: string | number
3291
+ ```
3292
+
3026
3293
  A conditional value keeps its `?` through the variable, and through a `??` or a ternary. With `$loaded = $this->whenLoaded('author')`, `'author' => $loaded ?? 'none'` publishes `author?: User | string`: a missing value isn't `null`, so `??` returns it, and Laravel drops the key.
3027
3294
 
3028
3295
  A closure or arrow-function parameter with the same name doesn't affect the outer variable. Inside its own closure, the parameter holds its own value:
@@ -3041,7 +3308,65 @@ public function toArray(Request $request): array
3041
3308
 
3042
3309
  A closure that captures the variable by value, with `use ($member)`, and reassigns it doesn't change the outer variable either. Only `use (&$member)` does. An arrow function never does.
3043
3310
 
3044
- A variable you write more than once publishes `unknown`, because the package can't tell which value reaches the response. That includes a second assignment inside an `if` or a loop, a `foreach` that assigns it, a `catch`, `unset()`, `static` or `global`, and changes through `.=`, `++`, or a reference. It also includes passing the variable to a by-reference parameter, such as `preg_match()`'s `$matches`, `settype()`, `parse_str()`, or one of your own methods. A variable assigned only inside an `if`, a loop, or another block also publishes `unknown`. Variables assigned inside a closure body follow the same rules within that closure. A reassignment inside an `if` branch that ends in `return` or `throw` applies only inside that branch, so the code after it keeps reading the original variable.
3311
+ A variable you write more than once publishes every value that can reach the read. A write that always runs replaces the value before it, and a write inside an `if`, a loop, a `try`, or a `catch` joins it:
3312
+
3313
+ ```php
3314
+ public function toArray(Request $request): array
3315
+ {
3316
+ $status = 'draft';
3317
+
3318
+ if ($this->is_pinned) {
3319
+ $status = 1;
3320
+ }
3321
+
3322
+ $first = null;
3323
+
3324
+ foreach ($this->comments as $comment) {
3325
+ if ($comment->content !== '') {
3326
+ $first = $comment->content;
3327
+
3328
+ break;
3329
+ }
3330
+ }
3331
+
3332
+ return [
3333
+ 'status' => $status, // status: string | number
3334
+ 'first' => $first, // first: string | null
3335
+ ];
3336
+ }
3337
+ ```
3338
+
3339
+ Each read sees only the writes that reach it. After `$x = $this->notes;`, a guard that returns `['early' => $x]` publishes `early: string | null`, and a later `$x = $this->resource->getKey(); return ['late' => $x];` publishes `late: number`. A write that reads the variable itself, as in `$label = $label.$this->title` or `$row = ['v' => $row]`, builds on the value before it.
3340
+
3341
+ A closure's or a helper's parameter follows the same rules. A write that always runs replaces the value the parameter was passed. A write inside a block is what later reads in that block see, and past the block it joins the value the parameter was passed. Here `$this->labelFor($this->title)` publishes `string | number`:
3342
+
3343
+ ```php
3344
+ private function labelFor(string $label)
3345
+ {
3346
+ if ($this->is_pinned) {
3347
+ $label = $this->id;
3348
+ }
3349
+
3350
+ return $label;
3351
+ }
3352
+ ```
3353
+
3354
+ A write to a closure's or helper's parameter inside a block, or a key one branch writes, that the package can't type is left out of the join, as [Values Left Out of a Union](#values-left-out-of-a-union) describes. On a plain local, such a write makes the read publish `unknown`.
3355
+
3356
+ A check that rules out `null` drops it from the reads it covers. With `$score = $this->rating` on a nullable column, `$score !== null ? $score : 'none'` publishes `string`, and so does `$this->when($score, fn () => $score)`, as an optional property.
3357
+
3358
+ Some variables still publish `unknown`:
3359
+
3360
+ - One a reference can write, through `use (&$x)`, `$alias = &$x`, `global` or `static`
3361
+ - One you change with `.=`, `++` or another compound assignment, apart from adding an array with `+=` as described below
3362
+ - One an `unset()` may remove
3363
+ - One you pass to a by-reference parameter that can change the value's form, such as `settype()`, `parse_str()`, or one of your own methods
3364
+
3365
+ Variables assigned inside a closure body follow the same rules within that closure. A reassignment inside an `if` branch that ends in `return` or `throw` applies only inside that branch, so the code after it keeps reading the original variable.
3366
+
3367
+ `preg_match()` writes its `$matches` as a list of strings. After `preg_match('/(\w+)-(\d+)/', $this->slug, $matches)`, both `$matches` and `$matches ?? []` publish `string[]`. A pattern with a named group, or a call that passes flags such as `PREG_OFFSET_CAPTURE`, writes the groups keyed by name or nested. The package doesn't type those groups, so `$matches ?? []` publishes `never[]`. A call that may not run, such as one inside an `if`, types `$matches` only when nothing else writes the variable.
3368
+
3369
+ A literal key read on a variable that holds an array shape takes that key's type. With `$row = ['a' => 1, 'b' => 'x']`, `$row['b']` publishes `string`, and `$row['c'] ?? null`, a key the shape lacks, publishes `null`. A `map()` parameter and a method whose `@return` declares a shape work the same way, so `$this->pair()[1]` on a method declared `@return array{int, string}` publishes `string`.
3045
3370
 
3046
3371
  A by-reference built-in that keeps the value's form keeps its type:
3047
3372
 
@@ -3066,13 +3391,27 @@ sort($original); // $copy keeps the type $original had before the sort
3066
3391
 
3067
3392
  A call on one of a local's keys, such as `sort($groups['x'])`, keeps the local's type when it keeps that key's form.
3068
3393
 
3069
- These rules cover a variable you read as a value. For a variable that `toArray()` returns, the package follows each write instead, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes.
3394
+ A variable you build with key writes or `+=` and read as a value publishes the keys written before the read:
3395
+
3396
+ ```php
3397
+ $meta = ['id' => $this->id];
3398
+ $meta['name'] = $this->name;
3399
+ $early = ['meta' => $meta];
3400
+ $meta['late'] = true;
3401
+
3402
+ return [
3403
+ 'meta' => $meta, // meta: { id: number; name: string; late: boolean }
3404
+ 'early' => $early, // early: { meta: { id: number; name: string } }
3405
+ ];
3406
+ ```
3407
+
3408
+ For a variable that `toArray()` returns, the package follows each write the same way, as [Building the Array in a Variable](#building-the-array-in-a-variable) describes.
3070
3409
 
3071
3410
  To type a variable the package can't read, annotate its assignment. See [Typing a Variable With `@var`](#typing-a-variable-with-var).
3072
3411
 
3073
3412
  ##### Narrowing With `instanceof`
3074
3413
 
3075
- An early-exit `instanceof` guard narrows a variable for every statement after it. Here `attachable` is a `morphTo`, so `$parent` can hold several models until the guard proves it holds a `Post`:
3414
+ An early-exit `instanceof` guard narrows a variable for the statements after it, up to the end of the block it sits in. Here `attachable` is a `morphTo`, so `$parent` can hold several models until the guard proves it holds a `Post`:
3076
3415
 
3077
3416
  ```php
3078
3417
  $record = $this->attachable;
@@ -3104,21 +3443,35 @@ export interface AttachmentResource {
3104
3443
  }
3105
3444
  ```
3106
3445
 
3107
- A guard narrows a variable only when all of these hold:
3446
+ An `if` narrows a variable wherever its test is proven:
3447
+
3448
+ - **After a guard**: an `if` whose body ends in `return` or `throw` narrows the reads after it, up to the end of the block it sits in. Inside a loop, so does one whose body ends in `continue` or `break`. A guard nested in a loop or in another `if` narrows only the rest of that block.
3449
+ - **Inside a positive test**: `if ($parent instanceof Post) { ... }` narrows the reads in its block. An `elseif` or `else` sees the earlier tests fail, so the `else` of `if (! $parent instanceof Post) { ... }` reads `Post`.
3450
+
3451
+ ```php
3452
+ $owner = $this->imageable;
3453
+ $data = [];
3454
+
3455
+ if ($owner instanceof Post) {
3456
+ $data['post_title'] = $owner->title;
3457
+ } elseif ($owner instanceof User) {
3458
+ $data['user_email'] = $owner->email;
3459
+ }
3460
+
3461
+ return $data; // post_title?: string; user_email?: string
3462
+ ```
3463
+
3464
+ The test can be one `instanceof`, negated or not, or an `||` chain of tests on the same variable, which narrows to any of their classes. A positive test can also join tests with `&&`. A positive test whose `||` joins two different variables narrows neither. A guard whose negated tests are joined with `||` narrows each, and one joined with `&&` narrows none. The test must read a local variable, a closure parameter, or a `foreach` value variable, not a property such as `$this->author`.
3108
3465
 
3109
- - The `if` sits at the top level of the method or closure body.
3110
- - The `if` has no `else` or `elseif`, and its body ends with `return` or `throw`.
3111
- - The condition is a negated test such as `! $parent instanceof Post`, alone or in an `||` chain. A chain joined with `&&` narrows nothing.
3112
- - The test reads a local variable or a closure parameter, not a property such as `$this->author`.
3113
- - Nothing writes the variable after the guard. A write before the guard doesn't matter, since the guard tests the value it leaves.
3466
+ A write to the variable between the test and the end of what it narrows cancels the narrowing, even for the reads before that write. A write through one of its members keeps the narrowing when it stores a literal the member's column holds, such as `$parent->title = 'Draft'`, or names no column or relation, such as `$parent->touched = true`. A write before the test doesn't matter, since the test checks the value it leaves.
3114
3467
 
3115
- The guard narrows only the reads after it. A read in the guard's own body, or in a `return` placed before the guard, still sees every class the variable can hold. A positive test, such as `if ($parent instanceof Post) { ... }`, narrows nothing, not even inside its own body.
3468
+ A read in a guard's own body, in a `return` placed before the guard, or in the `if` condition itself still sees every class the variable can hold.
3116
3469
 
3117
- Narrowing applies to reads through the variable, such as `$parent->title`. The variable's own value, as in `'parent' => $parent`, keeps its full union type.
3470
+ Narrowing applies to reads through the variable, such as `$parent->title`. A local's own value, as in `'parent' => $parent`, keeps its full union type. A closure parameter bound to one model is the exception: under a test for a published subclass of that model, its own value publishes the subclass, so `$this->whenLoaded('post', fn ($post) => $post instanceof DraftPost ? $post : null)` publishes `DraftPost | null`.
3118
3471
 
3119
- An `instanceof` ternary on a variable narrows its true arm the same way, as `record_title` above shows, and so does an `||` chain of tests on that variable. A negated test, such as `! $post instanceof Post ? null : $post->title`, narrows the false arm instead.
3472
+ An `instanceof` ternary on a variable narrows its true arm the same way, as `record_title` above shows, and so does an `||` chain of tests on that variable. A negated test, such as `! $post instanceof Post ? null : $post->title`, narrows the false arm instead. A ternary that tests a chain of property reads on `$this` narrows reads through the same chain in its arm, so `$this->imageable instanceof Post ? $this->imageable->getKey() : null` publishes `number | null`.
3120
3473
 
3121
- A ternary that tests `$this->resource` against one model narrows the backing model for its proven arm, so a relation that only a subclass declares resolves there. On a `Team` resource, `$this->resource instanceof SubscribedTeam ? $this->resource->subscriber?->name : null` publishes `string | null`.
3474
+ A test that checks `$this->resource` against one model narrows the backing model wherever it's proven: in a ternary's arm, in an `if` block, or after a guard. So a relation that only a subclass declares resolves there. On a `Team` resource, `$this->resource instanceof SubscribedTeam ? $this->resource->subscriber?->name : null` publishes `string | null`. A method of the resource that the proven code calls reads the narrowed model too, so `$this->resource instanceof SubscribedTeam ? $this->subscriberName() : null` publishes `string | null` when `subscriberName()` returns `$this->resource->subscriber?->name`. In a resource collection, the same test narrows the collected items to the paginator it names, as [Reading `$this->resource`](#reading-this-resource) shows.
3122
3475
 
3123
3476
  A variable assigned from an `instanceof` ternary keeps the narrowing for every read through it. The test can be an `||` chain of `instanceof` checks. Here `imageable` is a `morphTo` whose possible models include one with a string key:
3124
3477
 
@@ -3144,9 +3497,9 @@ return [
3144
3497
  These forms don't narrow:
3145
3498
 
3146
3499
  - **The ternary's own value**: `'either' => $either` publishes the whole union. Only reads through the variable narrow.
3147
- - **A read inside the arm when the test is on a property**: `$this->imageable instanceof Post ? $this->imageable->getKey() : null` stays `number | string | null`. Assign the ternary to a variable, and read through that variable instead.
3500
+ - **An `if` that tests a property**: inside `if ($this->imageable instanceof Post) { ... }`, `$this->imageable` still reads every model the `morphTo` can hold. Assign it to a local and test that instead.
3148
3501
  - **A test on a different spelling of the arm's value**: a variable bound to a ternary that tests `$this->resource->imageable` against a `$this->imageable` arm isn't narrowed.
3149
- - **Mixed conditions**: a test joined with `&&`, or an `||` chain that mixes negated and plain tests.
3502
+ - **Mixed conditions in a ternary**: a test joined with `&&`, or an `||` chain that mixes negated and plain tests.
3150
3503
  - **The arm the test doesn't prove**: `$this->resource instanceof SubscribedTeam ? null : $this->resource->subscriber` publishes `unknown`, since `Team` has no `subscriber` relation.
3151
3504
 
3152
3505
  ##### Typing a Variable With `@var`
@@ -3163,7 +3516,7 @@ return [
3163
3516
  ];
3164
3517
  ```
3165
3518
 
3166
- It also restores a value the package would otherwise drop. Without the annotation, `$picked` below publishes `null`, because the package leaves out a ternary arm it can't type:
3519
+ It also restores a value the package would otherwise drop. Without the annotation, `$picked` below publishes `null`, because the package [leaves out a ternary arm it can't type](#values-left-out-of-a-union):
3167
3520
 
3168
3521
  ```php
3169
3522
  /** @var string|null $picked */
@@ -3172,13 +3525,15 @@ $picked = $this->id > 0 ? json_decode('"x"') : null; // string | null
3172
3525
 
3173
3526
  The annotation follows these rules:
3174
3527
 
3175
- - **Placement**: it sits on a `$x = ...;` statement at the top level of the method or closure body. It names the variable, as in `/** @var CartTotals $totals */`, or names none, as in `/** @var CartTotals */`.
3176
- - **Span**: it types the reads after that statement, up to the next statement that writes the variable. A loop that writes the variable ends the span where the loop starts. So an annotation also types a variable you reassign, until its next write.
3528
+ - **Placement**: it sits on a `$x = ...;` statement anywhere in the method or closure body, including inside an `if` or a loop. It names the variable, as in `/** @var CartTotals $totals */`, or names none, as in `/** @var CartTotals */`.
3529
+ - **Span**: it types the reads after that statement, up to the next statement that writes the variable. A loop that writes the variable ends the span where the loop starts. So an annotation also types a variable you reassign, until its next write. Inside a block, it types the reads after it in that block. Past the block, where the variable held a value before it, the annotated type joins that value. Where the variable held none, reads past the block aren't typed. With `$post = null;` before an `if` whose annotated assignment reads `/** @var Post|null $post */`, `$post?->title` after the `if` publishes `string | null`.
3177
3530
  - **Precedence**: it applies only where the package's own reading of the value is `unknown`, or is only the `null` left after an arm it can't type was dropped. Any other reading stands, whatever the annotation says: `/** @var int $n */ $n = $this->title;` still publishes `string`. To override a type the package got wrong, use [`#[TsCasts]`](#overriding-property-types-with-tscasts).
3178
3531
 
3179
3532
  A conditional value stays optional, so `/** @var User $reviewer */ $reviewer = $this->whenLoaded('reviewer');` publishes `reviewer?: User`.
3180
3533
 
3181
- A closure parameter you reassign reads the new value from that statement on, when the value or an annotation names its class. In `function (User $author)`, `$author = $author->profile;` makes the reads after it use `Profile`. The package can't tell which class `$author->comments->find(1)` returns, so after `$author = $author->comments->find(1);` the reads keep using `User` until you annotate the assignment with `/** @var Comment $author */`. A `foreach` variable bound to a model keeps reading that model.
3534
+ A closure parameter you reassign reads the new value from that statement on, when the value or an annotation names its class. In `function (User $author)`, `$author = $author->profile;` makes the reads after it use `Profile`. `find()` with one literal key returns one of the collection's models or `null`. After `$author = $author->comments->find(1);`, `$author?->content` publishes `string | null`, and `$author->name` publishes `unknown`, since a comment has no `name`. A read of the variable itself after that write publishes `unknown`, as `first()` does.
3535
+
3536
+ A write the package can't type keeps a model parameter's model, so after `$author = $this->normalize($author);`, where `normalize()` declares no return type, both `$author->name` and `return $author;` still read `User`. Annotate such an assignment, as in `/** @var Comment $author */`, and the reads follow the annotation. A write of a typed value is read as that value, so after `$author = $author->name;`, `return $author;` publishes `string`. A parameter that holds a plain value takes what any write returns, so after `$title = json_decode($title);`, `return $title;` publishes `unknown`. A `foreach` variable bound to a model keeps reading that model.
3182
3537
 
3183
3538
  The annotation's type counts only when it's built from these forms, and when every part of it resolves:
3184
3539
 
@@ -3194,7 +3549,7 @@ Any other type is ignored, so write `list<int>` instead of `int[]`. A model or e
3194
3549
 
3195
3550
  #### Collection Pipelines
3196
3551
 
3197
- A chain of collection methods keeps its element type to the end, whether it starts at a relation or at `collect()`:
3552
+ A chain of collection methods keeps its element type to the end, whether it starts at a relation, a local, a query, or `collect()`:
3198
3553
 
3199
3554
  ```php
3200
3555
  return [
@@ -3221,16 +3576,52 @@ export interface PostResource {
3221
3576
 
3222
3577
  These helpers and methods publish as follows:
3223
3578
 
3224
- - **`all()` and `values()`**: a collection and the array behind it both publish `X[]`, so `all()` changes nothing. A method that breaks sequential keys, such as `filter()`, `sortBy()`, or `keyBy()`, adds a `Record<string, X>` arm, because `json_encode()` writes such a collection as an object. `values()` restores sequential keys and removes that arm.
3579
+ - **`all()` and `values()`**: a collection and the array behind it both publish `X[]`, so `all()` changes nothing. A method that breaks sequential keys, such as `filter()`, `sortBy()`, or `keyBy()`, adds a `Record<string, X>` arm, because `json_encode()` writes such a collection as an object. The arm stays through a local and through a later `map()`. `values()` restores sequential keys and removes that arm.
3225
3580
  - **`collect()`**: the element type comes from the argument, and the `map()` parameter holds that element, which is why `$word` above is a `string`. On its own, `collect([...])` publishes the list or object its array encodes as, such as `number[]` for `collect([1, 2])` or `{ title: string }` for `collect(['title' => $this->title])`. `collect()` with no argument publishes `never[]`. A bare array literal publishes the same way, so `['a', 'b']` publishes `string[]`. A list holding an element the package can't type publishes `unknown[]`.
3226
3581
  - **`data_get()`**: `data_get($target, 'a.b')` publishes what `$target?->a?->b` would. A default joins the type instead of removing `null`, because `data_get()` returns the default only when the key is missing, not when its value is `null`.
3227
- - **Typed `map()` parameters**: a model type hint on a `map()` parameter types every read through it, chained and nullsafe reads included, when you call `map()` on a variable such as a local or a `whenLoaded()` parameter. With `$rows = $this->resource->getRelation('comments')`, `$rows->map(fn (Comment $comment) => $comment->user?->name ?: null)->all()` publishes `(string | null)[]`. A relation chain such as `$this->comments->map(...)` uses the relation's model the same way. On a `collect(...)` root, or on a `map()` called straight on a method's result, such as `$this->resource->getRelation('comments')->map(...)`, the parameter holds no model, so reads through it publish `unknown`.
3582
+ - **`map()` parameters**: the callback's parameter holds the collection's element, with or without a type hint, whether the collection comes from a relation, a local, a `whenLoaded()` parameter, `getRelation()`, a query's `get()`, or `collect()`. Every read through it is typed, chained and nullsafe reads included. A class type hint, such as `fn (Comment $comment)` or a value object's class, types the parameter whatever the collection holds. A write that replaces the parameter is followed into the body.
3583
+
3584
+ Here `PromoCode` is a value object with a `string` property `code`:
3585
+
3586
+ ```php
3587
+ public function toArray(Request $request): array
3588
+ {
3589
+ $rows = $this->comments;
3590
+ $byContent = $this->comments->keyBy('content');
3591
+
3592
+ return [
3593
+ 'collected_reads' => collect($this->comments)->map(fn ($comment) => ['content' => $comment->content, 'who' => $comment->user?->name])->all(),
3594
+ 'local_rows' => $rows->map(fn ($comment) => ['who' => $comment->user?->name]),
3595
+ 'author_names' => $rows->map(function (Comment $comment) {
3596
+ $comment = $comment->user;
3597
+
3598
+ return $comment->name;
3599
+ }),
3600
+ 'keyed_rows' => $byContent->map(fn (Comment $comment) => ['id' => $comment->id])->all(),
3601
+ 'query_rows' => Comment::query()->get()->map(fn (Comment $comment) => ['id' => $comment->id])->all(),
3602
+ 'codes' => collect([new PromoCode('a')])->map(fn (PromoCode $code) => ['id' => $code->code])->all(),
3603
+ ];
3604
+ }
3605
+ ```
3606
+
3607
+ Each map publishes its callback's shape:
3608
+
3609
+ ```typescript
3610
+ collected_reads: { content: string; who: string | null }[];
3611
+ local_rows: { who: string | null }[];
3612
+ author_names: string[];
3613
+ keyed_rows: { id: number }[] | Record<string, { id: number }>;
3614
+ query_rows: { id: number }[];
3615
+ codes: { id: string }[];
3616
+ ```
3617
+
3618
+ `Model::all()` names its model the same way, so `Post::all()->toResourceCollection()` publishes `PostResource[]`. `map()` on a paginator maps the models on its page, so with `$page = Post::query()->paginate();`, `$page->map(fn (Post $post) => ['id' => $post->id])` publishes `{ id: number }[]`.
3228
3619
 
3229
3620
  `concat($other)` keeps the type only when `$other` is exactly the same collection type. Concatenating `Comment[]` and `Tag[]` publishes `unknown`, since the result is a different collection, not a longer one. A `data_get()` key with a `*` segment also publishes `unknown`.
3230
3621
 
3231
3622
  A chain can start at `$this->resource` too. `$this->resource->comments->map(fn ($comment) => $comment->id)` publishes `number[]`, as `$this->comments->map(...)` does. A `?->` on `$this->resource` adds `| null` once, since a resource can wrap `null`. `$this->resource?->comments->map(fn ($comment) => $comment->id)` publishes `number[] | null`.
3232
3623
 
3233
- `first()`, `last()` and `firstWhere()` on a relation's collection return one of its models or `null`, so a read through them with `?->` is typed. `$this->comments->first()?->content` publishes `string | null`, and so does the same read after `last()` or `firstWhere('is_flagged', true)`. After a `first()` or `last()` call that passes a default, such as `first(null, 'none')`, the read publishes `unknown`, because Laravel returns that default when no model matches.
3624
+ `first()`, `last()` and `firstWhere()` on a collection of models return one of its models or `null`, so a read through them with `?->` is typed. That covers a relation's collection, a local holding one, and a variable an inline `@var Collection<int, Comment>` declares. `$this->comments->first()?->content` publishes `string | null`, and so does the same read after `last()`, `firstWhere('is_flagged', true)`, or `find()` with one literal key, such as `find(1)`. After a `first()` or `last()` call that passes a default, such as `first(null, 'none')`, the read publishes `unknown`, because Laravel returns that default when no model matches.
3234
3625
 
3235
3626
  ### Spreads and Inheritance
3236
3627
 
@@ -3305,6 +3696,77 @@ export interface BodylessOrderResource {
3305
3696
 
3306
3697
  The nearest class up the parent chain that declares a `toArray()` provides the shape, so inheritance several levels deep works. The backing model comes from the parent chain too: a resource with no `@mixin` or `@extends` tag of its own uses the nearest ancestor's, as step 3 of [How the Backing Model Is Resolved](#how-the-backing-model-is-resolved) describes. That keeps the inherited properties typed from their columns.
3307
3698
 
3699
+ The package reads the inherited body as PHP runs it for the child:
3700
+
3701
+ - `$this->` and `static::` reach the child, so a method, constant, or property the child overrides publishes the child's type. That includes a helper that `toArray()` spreads.
3702
+ - `self::` reaches the class that declares the body, and `parent::` reaches that class's parent.
3703
+ - A `private` member stays the one in the class that declares `toArray()`, because PHP never overrides one.
3704
+
3705
+ ```php
3706
+ class BaseCardResource extends JsonResource
3707
+ {
3708
+ public const KIND = 'card';
3709
+
3710
+ public function toArray(Request $request): array
3711
+ {
3712
+ return [
3713
+ 'title' => $this->title(),
3714
+ 'kind' => static::KIND,
3715
+ 'label' => self::label(),
3716
+ 'weight' => $this->weight(),
3717
+ ];
3718
+ }
3719
+
3720
+ public function title(): int|string
3721
+ {
3722
+ return 0;
3723
+ }
3724
+
3725
+ public static function label(): int|string
3726
+ {
3727
+ return 0;
3728
+ }
3729
+
3730
+ private function weight(): int
3731
+ {
3732
+ return 1;
3733
+ }
3734
+ }
3735
+
3736
+ class NoticeCardResource extends BaseCardResource
3737
+ {
3738
+ public const KIND = 7;
3739
+
3740
+ public function title(): string
3741
+ {
3742
+ return 'Notice';
3743
+ }
3744
+
3745
+ public static function label(): string
3746
+ {
3747
+ return 'notice';
3748
+ }
3749
+
3750
+ public function weight(): string
3751
+ {
3752
+ return 'heavy';
3753
+ }
3754
+ }
3755
+ ```
3756
+
3757
+ `title` and `kind` come from `NoticeCardResource`. `label` keeps the parent's `string | number`, because `self::label()` calls `BaseCardResource::label()`, and `weight` keeps `number`, because `weight()` is private to `BaseCardResource`:
3758
+
3759
+ ```typescript
3760
+ export interface NoticeCardResource {
3761
+ title: string;
3762
+ kind: number;
3763
+ label: string | number;
3764
+ weight: number;
3765
+ }
3766
+ ```
3767
+
3768
+ `self::make()` and `self::collection()` in the inherited body build the child, as they do in PHP. So a `FeaturedCategoryResource` that inherits `'children' => self::collection($this->whenLoaded('children'))` from `CategoryResource` publishes `children?: FeaturedCategoryResource[]`. A method that returns `static`, called through `self::` or `parent::`, returns the child too.
3769
+
3308
3770
  If no class in the chain declares a `toArray()`, the resource publishes the model's properties, as [JsonResource Base Delegation](#jsonresource-base-delegation) describes. With no model either, the interface is empty, apart from any types `#[TsExtends]` adds. A `ResourceCollection` subclass with no `toArray()` still finds its element type as [Resource Collections](#resource-collections) describes.
3309
3771
 
3310
3772
  #### A `toArray()` From a Trait
@@ -3345,6 +3807,45 @@ export interface LabelResource {
3345
3807
 
3346
3808
  A subclass of `LabelResource` with no `toArray()` of its own publishes the same keys. A `ResourceCollection` can take its `toArray()` from a trait the same way.
3347
3809
 
3810
+ In the trait's `toArray()`, `self::` reaches the class that uses the trait, and `parent::` reaches that class's parent. `$this->` and `static::` reach the resource, as they do in an [inherited `toArray()`](#inheriting-a-parent-toarray). Here `TagCardResource` extends the `BaseCardResource` above:
3811
+
3812
+ ```php
3813
+ trait ShapesCard
3814
+ {
3815
+ public function toArray(Request $request): array
3816
+ {
3817
+ return [
3818
+ ...parent::toArray($request),
3819
+ 'label' => self::label(),
3820
+ 'kind' => static::KIND,
3821
+ ];
3822
+ }
3823
+ }
3824
+
3825
+ class TagCardResource extends BaseCardResource
3826
+ {
3827
+ use ShapesCard;
3828
+
3829
+ public const KIND = 'tag';
3830
+
3831
+ public static function label(): string
3832
+ {
3833
+ return 'tag';
3834
+ }
3835
+ }
3836
+ ```
3837
+
3838
+ `parent::toArray()` spreads `BaseCardResource`'s keys, and `label` and `kind` take `TagCardResource`'s types:
3839
+
3840
+ ```typescript
3841
+ export interface TagCardResource {
3842
+ title: string | number;
3843
+ kind: string;
3844
+ label: string;
3845
+ weight: number;
3846
+ }
3847
+ ```
3848
+
3348
3849
  #### JsonResource Base Delegation
3349
3850
 
3350
3851
  A resource with no `toArray()`, or whose `toArray()` returns `parent::toArray($request)`, publishes the backing model's columns, its appended accessors, and its relations, each relation an optional key. These follow the keys Laravel's `Model::toArray()` writes, with the differences below. A subclass of Laravel's `JsonApiResource` is the exception: it publishes the resource object it sends, as [JSON:API Resources](#jsonapi-resources) describes. This resource has no `toArray()`:
@@ -3579,19 +4080,147 @@ The variable can start from an array literal, as above, or from any of these:
3579
4080
  - `$this->only([...])` with a literal list of keys
3580
4081
  - `array_merge()` of array literals and `parent::toArray($request)` calls
3581
4082
  - A helper method on the resource that returns an array
4083
+ - A local you assign one of these once, as in `$data = $defaults;`
3582
4084
 
3583
4085
  A spread of `...$this->with($request)` or `...parent::with($request)` in `toArray()` adds the `$with` keys too.
3584
4086
 
3585
4087
  These rules decide each key:
3586
4088
 
3587
- - **A write inside a block**: a key first written inside an `if`, a loop, a `try` or `catch` block, or a `switch` case publishes optional, because that path may not run.
3588
- - **A key written more than once**: the key takes the type of its last write. `+=` adds only the keys the array doesn't have yet, and assigning a whole new array drops the keys written before it.
3589
- - **An `unset()`**: `unset($data['slug'])` removes the key. Inside a block, it makes the key optional instead.
4089
+ - **Branches**: each branch of an `if` chain holds its own value for a key. A key that every branch of a chain ending in `else` writes is required, with each branch's type. A key that only some branches write publishes optional, and a key set before the chain keeps that value as one more type. A branch that ends in `throw`, or in a `return` of anything but the variable, stays out.
4090
+ - **Loops**: a loop may run no times, so a key it first writes publishes optional, and a key it re-sets keeps the value it held before the loop as one more type.
4091
+ - **`try`, `catch`, and `switch`**: their bodies are read in order. A key first written in one publishes optional, and a key re-set in one takes its last write's type.
4092
+ - **A key written more than once in a row**: the key takes the type of its last write. `+=` adds only the keys the array doesn't have yet. Assigning a whole new array drops the keys written before it. Inside one branch, it replaces them for that branch only, so a key that one side lacks publishes optional.
4093
+ - **An `unset()`**: `unset($data['slug'])` removes the key, and so does `unset($data[$key])` when `$key` is a local you assign a string literal once. Inside a block, it makes the key optional instead. In `unset($data['name'], $data[$hidden])`, the package removes `name` but can't follow `$data[$hidden]`. An index signature from an [interpolated key](#interpolated-keys) stays after an `unset()` of a literal key it matches, since its value already admits `undefined`.
3590
4094
  - **Other `return` statements**: the variable counts as one branch beside the method's other returns, so a `return []` guard, or a returned array literal that leaves a key out, makes that key optional.
3591
4095
 
3592
- The package doesn't follow `$data[] = ...`, a key computed at runtime such as `$data[$key]`, or a nested key such as `$data['meta']['label']`, whether written or passed to `unset()`. It also reads the method in one pass. A key written after an early `return $data;` publishes required when that write always runs, though the early return sends the array without it. In either case, return an array literal on each path, or list the keys with [`#[TsCasts]`](#overriding-property-types-with-tscasts), which can also mark a key optional.
4096
+ Here each key holds the value of every branch that can write it:
4097
+
4098
+ ```php
4099
+ public function toArray(Request $request): array
4100
+ {
4101
+ $data = ['id' => $this->id, 'label' => $this->sort_order];
4102
+
4103
+ if ($this->is_active) {
4104
+ $data['mode'] = 1;
4105
+ } else {
4106
+ $data['mode'] = 'off';
4107
+ }
4108
+
4109
+ if ($this->sort_order === 1) {
4110
+ $data['tier'] = 'first';
4111
+ $data['first_only'] = true;
4112
+ } elseif ($this->sort_order === 2) {
4113
+ $data['tier'] = 2;
4114
+ } else {
4115
+ $data['tier'] = false;
4116
+ }
4117
+
4118
+ if ($this->description !== null) {
4119
+ $data['label'] = $this->name;
4120
+ $data['described'] = true;
4121
+ }
4122
+
4123
+ return $data;
4124
+ }
4125
+ ```
4126
+
4127
+ On a `Category` resource, the variable publishes:
4128
+
4129
+ ```typescript
4130
+ export interface CategorySummaryResource {
4131
+ id: number;
4132
+ label: number | string;
4133
+ mode: number | string;
4134
+ tier: string | number | boolean;
4135
+ first_only?: boolean;
4136
+ described?: boolean;
4137
+ }
4138
+ ```
4139
+
4140
+ A value one branch writes that the package can't type is left out of the key's type, as [Values Left Out of a Union](#values-left-out-of-a-union) describes.
4141
+
4142
+ The package doesn't follow `$data[] = ...`, a key computed at runtime, such as `$data[$key]` where `$key` isn't a local holding one string literal, or a nested key such as `$data['meta']['label']`, whether written or passed to `unset()`. It also reads the method in one pass. A key written after an early `return $data;` publishes required when that write always runs, though the early return sends the array without it. A `continue` or `break` isn't followed either, so in a loop body, a write after an `if` that ends in `continue` replaces the `if`'s write, though Laravel can send the `if`'s value. In each case, return an array literal on each path, or list the keys with [`#[TsCasts]`](#overriding-property-types-with-tscasts), which can also mark a key optional.
4143
+
4144
+ `+` publishes PHP's array union, where the left side's keys win and the right side adds the keys it lacks. That holds in a key's value, so `['code' => 'in'] + ['code' => 0, 'lane' => 2]` publishes `{ code: string; lane: number }`, and in a whole return, such as `return parent::toArray($request) + ['note' => 'none'];`. Either side can be a local holding an array: with `$defaults = ['note' => 'none', 'id' => 'x']`, `return ['id' => $this->id] + $defaults;` publishes `id: number` and `note: string`.
4145
+
4146
+ A helper that you pass the array to, and that returns it, keeps the array's keys and adds the keys it writes. A vague `@return array<string, mixed>` on the helper doesn't hide them:
4147
+
4148
+ ```php
4149
+ public function toArray(Request $request): array
4150
+ {
4151
+ $data = [
4152
+ 'id' => $this->id,
4153
+ 'title' => $this->title,
4154
+ 'url' => url("/posts/{$this->id}"),
4155
+ 'disabled' => false,
4156
+ ];
4157
+
4158
+ return $this->guard($data);
4159
+ }
4160
+
4161
+ /**
4162
+ * @param array<string, mixed> $data
4163
+ * @return array<string, mixed>
4164
+ */
4165
+ private function guard(array $data): array
4166
+ {
4167
+ if ($this->trashed()) {
4168
+ $data['url'] = null;
4169
+ $data['disabled'] = true;
4170
+ }
4171
+
4172
+ return $data;
4173
+ }
4174
+ ```
4175
+
4176
+ The resource publishes the array's keys, with the helper's writes joined in:
4177
+
4178
+ ```typescript
4179
+ export interface PostLinkResource {
4180
+ id: number;
4181
+ title: string;
4182
+ url: string | null;
4183
+ disabled: boolean;
4184
+ }
4185
+ ```
4186
+
4187
+ The same holds when you use the helper's result as a value, so `'link' => $this->guard(['url' => url('/posts'), 'disabled' => false])` publishes `link: { url: string | null; disabled: boolean }`.
4188
+
4189
+ When a helper's array starts from a value the package can't read, such as `$request->all()`, a key that holds the helper's result publishes the keys the helper writes, plus an index signature for the rest. When all the package can read of a helper's array is its `@return array<string, mixed>`, such a key publishes `Record<string, unknown>`:
4190
+
4191
+ ```php
4192
+ public function toArray(Request $request): array
4193
+ {
4194
+ return [
4195
+ 'filters' => $this->filters($request),
4196
+ 'options' => $this->options(),
4197
+ ];
4198
+ }
4199
+
4200
+ /** @return array<string, mixed> */
4201
+ private function filters(Request $request): array
4202
+ {
4203
+ $filters = $request->all();
4204
+ $filters['page'] = 1;
4205
+
4206
+ return $filters;
4207
+ }
3593
4208
 
3594
- `+` publishes PHP's array union, where the left side's keys win and the right side adds the keys it lacks. That holds in a key's value, so `['code' => 'in'] + ['code' => 0, 'lane' => 2]` publishes `{ code: string; lane: number }`, and in a whole return, such as `return parent::toArray($request) + ['note' => 'none'];`.
4209
+ /** @return array<string, mixed> */
4210
+ private function options(): array
4211
+ {
4212
+ return json_decode($this->content, true);
4213
+ }
4214
+ ```
4215
+
4216
+ `filters` keeps the key the helper writes, and `options` publishes a record:
4217
+
4218
+ ```typescript
4219
+ export interface PostFiltersResource {
4220
+ filters: { page: number; [key: string]: unknown };
4221
+ options: Record<string, unknown>;
4222
+ }
4223
+ ```
3595
4224
 
3596
4225
  #### Return Branches and `@return` Shapes
3597
4226
 
@@ -3769,6 +4398,8 @@ members?: (Omit<User, "flag"> & { flag: boolean })[];
3769
4398
 
3770
4399
  The `Omit<>` matters. In PHP the later key wins, so `'flag'` replaces whatever the spread contributed. TypeScript's `&` would instead intersect both, and turn a conflicting key into `never`. When one literal holds several spreads, each spread's `Omit<>` removes every key that a later spread or an explicit key overwrites, in source order.
3771
4400
 
4401
+ The spread uses the model the variable holds, on any collection a `map()` runs over. `collect($this->comments)->map(fn (Comment $comment) => [...$comment->toArray(), 'flag' => true])->all()` publishes `(Omit<Comment, "flag"> & { flag: boolean })[]`. A local inside the callback spreads its own model, so `$author = $comment->user;` followed by `[...$author->toArray(), 'x' => 1]` publishes `Omit<User, "x"> & { x: number }` for each comment.
4402
+
3772
4403
  At the top level of `toArray()`, a spread with no key flattens into the resource's own properties instead. `...$this->user->toArray()` adds the user's properties to the interface, and `...PostResource::make($this->post)->resolve()` adds the post resource's. A collection's `...$this->tags->toArray()` adds a `[key: number]` index signature.
3773
4404
 
3774
4405
  The intersection references the `{Model}` interface instead of copying its shape. That comes close to what `toArray()` returns at runtime, with two differences:
@@ -3865,7 +4496,7 @@ replies: Comment[];
3865
4496
  kept: Comment[] | null;
3866
4497
  ```
3867
4498
 
3868
- A `?->` on `$this->resource` adds `| null` once, because a resource can wrap `null`. `$this->resource?->comments->only([1, 2])` publishes `Comment[] | null`.
4499
+ A `?->` on `$this->resource` adds `| null` once, because a resource can wrap `null`. `$this->resource?->comments->only([1, 2])` publishes `Comment[] | null`. A variable that holds the relation's collection filters the same way, so `'picked' => $this->whenLoaded('comments', fn ($comments) => $comments->only([1, 2]))` publishes `picked?: Comment[]`.
3869
4500
 
3870
4501
  An accessor that returns an Eloquent collection of models filters the same way. It publishes a list of those models, such as `Comment[]`, whatever key type the accessor declares.
3871
4502
 
@@ -4154,6 +4785,21 @@ Laravel throws when the items are a plain collection, or a paginator without tha
4154
4785
 
4155
4786
  If the collection always receives one kind of paginator, redeclare `$resource` with it. With `/** @var LengthAwarePaginator<int, UserResource> */ public $resource;`, `page` publishes `LengthAwarePaginator<UserResource>`.
4156
4787
 
4788
+ An `instanceof` test on `$this->resource` narrows the items to the paginator it names, in a ternary's arm, inside an `if` block, or after a guard. A read outside what the test proves keeps every shape:
4789
+
4790
+ ```php
4791
+ public function toArray(Request $request): array
4792
+ {
4793
+ if ($this->resource instanceof LengthAwarePaginator) {
4794
+ return ['pager' => $this->resource];
4795
+ }
4796
+
4797
+ return ['pager' => null];
4798
+ }
4799
+ ```
4800
+
4801
+ Here `pager` publishes `LengthAwarePaginator<UserResource> | null`.
4802
+
4157
4803
  A call the collection forwards to `$this->resource`, such as `$this->first()` or `$this->total()`, publishes the same type. In a [key-preserving collection](#key-preserving-collections), the list type is `Record<string, UserResource>`. When no singular resource matches, each type holds `unknown`, such as `unknown[]` and `LengthAwarePaginator<unknown>`.
4158
4804
 
4159
4805
  The package doesn't follow a collection pipeline on `$this->resource`, such as `map()`, `pluck()` or `values()`, or a read on the item `first()` returns, such as `$this->resource->first()?->name`. Each publishes `unknown`. Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
@@ -4338,7 +4984,7 @@ The package already types these shapes without an override:
4338
4984
  - A collection chain, `data_get()`, and `only([...])` on any model. See [Collection Pipelines](#collection-pipelines) and [Attribute Filters on Any Model](#attribute-filters-on-any-model).
4339
4985
  - A key that only some branches return, or one that a spread method's `@return` describes. See [Return Branches and `@return` Shapes](#return-branches-and-return-shapes).
4340
4986
 
4341
- `#[TsCasts]` is the right tool when the frontend owns the type and it needs its own import, or when a shape is dynamic.
4987
+ `#[TsCasts]` is the right tool when the frontend owns the type and it needs its own import, or when a shape is dynamic. To type every value of a class that way, put [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) on the class instead.
4342
4988
 
4343
4989
  Use `#[TsCasts]` to override a property's type, or to add a property that `toArray()` doesn't return:
4344
4990
 
@@ -4461,6 +5107,26 @@ A `when()`, ternary, `mergeWhen()`, `transform()`, `if` block or earlier `return
4461
5107
 
4462
5108
  A resource built directly around a relation gets the `| null` only when the package can type that relation. A relation the model doesn't declare, a relation to a model the package doesn't publish, and a `morphTo` with no resolvable target publish without it. Inside a `whenLoaded()` closure, the relation's own rule applies instead, so `$this->whenLoaded('parent', fn ($parent) => CategoryResource::make($parent))` publishes `CategoryResource | null` whenever `parent` can load `null`. In that closure, a relation the model doesn't declare counts as one that can load `null` while `nullable_relations` is on.
4463
5109
 
5110
+ A `whenLoaded()` value that hands the relation to a resource's `collection()` is the exception. Only a to-many relation, which loads as a list, fits there, so `$this->whenLoaded('branches', CategoryResource::collection(...))` publishes `branches?: CategoryResource[]` even when the package can't read `branches`.
5111
+
5112
+ Inside a `map()`, Laravel turns a nested resource with a `null` payload into `null` only where it reaches the mapped items as an array, so the `| null` depends on how the chain ends. On a `Team` resource, where `members` holds users and `profile` is a `HasOne` relation:
5113
+
5114
+ ```php
5115
+ 'profiles' => $this->members->map(fn (User $member) => ['profile' => new ProfileResource($member->profile)]),
5116
+ 'profiles_all' => $this->members->map(fn (User $member) => ['profile' => new ProfileResource($member->profile)])->all(),
5117
+ ```
5118
+
5119
+ Only the chain that ends in `->all()` adds `| null`:
5120
+
5121
+ ```typescript
5122
+ interface TeamResource {
5123
+ profiles: { profile: ProfileResource }[];
5124
+ profiles_all: { profile: ProfileResource | null }[];
5125
+ }
5126
+ ```
5127
+
5128
+ Without `->all()`, or through `->values()`, a member with no profile makes Laravel throw instead of sending `null`.
5129
+
4464
5130
  To turn off nullable relation detection everywhere:
4465
5131
 
4466
5132
  ```php
@@ -5018,6 +5684,8 @@ An entry publishes its type exactly as written, without the `Partial<>` a model
5018
5684
 
5019
5685
  You can also put `#[TsCasts]` on `broadcastWith()`. It works the same way as on the class, and the class's entry wins when both name a key.
5020
5686
 
5687
+ To type every property that holds a given class, in every event, put [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) on that class instead of an entry on each event.
5688
+
5021
5689
  ### Extending Interfaces: Global Config vs. `#[TsExtends]`
5022
5690
 
5023
5691
  An event interface can extend shared interfaces through config, through an attribute, or through both at once.
@@ -5326,7 +5994,7 @@ The response for `Status::Published`, with two instance methods, looks like this
5326
5994
 
5327
5995
  Each instance method, marked with `#[TsEnumMethod]` or included by `enums.auto_include_methods`, adds a top-level key that holds the method's value for this case. Each static method, marked with `#[TsEnumStaticMethod]` or included by `enums.auto_include_static_methods`, adds a top-level key that holds its return value.
5328
5996
 
5329
- Each method key holds the same value as the published enum, as `json_encode()` writes it. A method that throws for the case, or returns a value `json_encode()` can't write, sends `null`. [Object and Array Values](https://tolki.abe.dev/ts/enums.html#object-and-array-values) shows how an object becomes JSON, and the one kind of array that the response sends as a list while the published enum holds an object.
5997
+ Each method key holds the same value as the published enum, as `json_encode()` writes it. A method that throws for the case, or returns a value `json_encode()` can't write, sends `null`. [Object and Array Values](https://tolki.abe.dev/ts/enums.html#object-and-array-values) shows how an object or an array becomes JSON.
5330
5998
 
5331
5999
  The response therefore has the same keys as the object you get when you call `.from()` on the published enum with the same value.
5332
6000
 
@@ -5463,7 +6131,7 @@ When two enums share a class name, both imports get a namespace prefix, for the
5463
6131
 
5464
6132
  ## Excluding Content
5465
6133
 
5466
- Add the `#[TsExclude]` attribute to keep a class out of the TypeScript output, or to leave out one of its methods, accessors, relations, or controller actions. It works on enums, models, resources, form requests, broadcast events, and controllers. It's a PHP attribute only. It has no config key, and there's nothing to set up in `@tolki/ts`.
6134
+ Add the `#[TsExclude]` attribute to keep a class out of the TypeScript output, or to leave out one of its methods, accessors, relations, or controller actions. It works on enums, models, resources, form requests, broadcast events, and controllers. On a class with a [composed type](https://tolki.abe.dev/ts/custom-types.html#composed-types), it also stops the class composing. It's a PHP attribute only. It has no config key, and there's nothing to set up in `@tolki/ts`.
5467
6135
 
5468
6136
  ### `#[TsExclude]` Attribute
5469
6137
 
@@ -6569,6 +7237,7 @@ With `inertia.enabled` on (the default), the package builds the file from your m
6569
7237
  - **API resources**: a resource or resource collection is typed as the response Inertia sends for it, as [API Resources in Props](#api-resources-in-props) describes.
6570
7238
  - **`EnumResource` props**: a prop that wraps an enum in `EnumResource`, such as `'role' => EnumResource::make(Role::Admin)`, becomes `AsEnum<typeof Role>` when `enums.use_tolki_package` is on (the default), the same as in [API Resources](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource). With it off, the key keeps the enum's type alias (`role: RoleType`). The change applies per key, so another key that reads the enum directly keeps `RoleType`.
6571
7239
  - **Enum cases**: a bare case, such as `'defaultStatus' => Status::Draft`, is typed as the enum's type alias (`defaultStatus: StatusType`), which matches the value Laravel sends for a backed enum. The file imports the alias for you.
7240
+ - **Classes with `#[TsType]`**: a value of a class that has or inherits a `#[TsType]` is typed as that type, with its import, in shared data and page props alike. See [Custom Types](https://tolki.abe.dev/ts/custom-types.html).
6572
7241
  - **`errors`**: left out. `@inertiajs/core` already types `page.props.errors` as `Errors & ErrorBag`, and [`errorValueType`](#anatomy-of-the-generated-file) sharpens it. A `#[TsCasts]` or `@return` docblock entry named `errors` still adds one if you want it.
6573
7242
  - **The output file**: the result is written to `inertia-config.d.ts`. Set `inertia.augmentation_filename` to change the name.
6574
7243
 
@@ -6576,7 +7245,7 @@ With `inertia.enabled` on (the default), the package builds the file from your m
6576
7245
 
6577
7246
  When the package can't create an instance of the model, it reads the key type from the class, and publishes `unknown` if code works the key out. A `getAuthIdentifierName()` that works the column out in code, such as from config, publishes `unknown` too, and so does an override of `getAuthIdentifier()`, since only running your app shows which value the ID holds.
6578
7247
 
6579
- In a route's [page props](https://tolki.abe.dev/ts/routing.html#inertia-integration), `getKey()` on a route-bound model publishes the model's key type with no `| null`, because Laravel binds only a saved row. With a `Post $post` action parameter, `'post_id' => $post->getKey()` publishes `post_id: number`.
7248
+ In a route's [page props](https://tolki.abe.dev/ts/routing.html#inertia-integration), `getKey()` on a route-bound model publishes the model's key type with no `| null`, because Laravel binds only a saved row. With a `Post $post` action parameter, `'post_id' => $post->getKey()` publishes `post_id: number`. A relation read on the parameter is typed by the models it loads, so `'comments' => $post->comments` publishes `comments: Comment[]`.
6580
7249
 
6581
7250
  A key whose ternary arms wrap different enums, such as `$cond ? EnumResource::make(Role::Admin) : EnumResource::make(Status::Draft)`, renders as `RoleType | StatusType` with no import for either name. Your build then fails with a `TS2304` error for each. Give both arms the same enum, or override that key with a `#[TsCasts]` entry that has an `import`.
6582
7251
 
@@ -6825,7 +7494,7 @@ The [Configuration Reference](https://tolki.abe.dev/ts/configuration-reference.h
6825
7494
 
6826
7495
  ## Modular Publishing
6827
7496
 
6828
- The package writes every TypeScript file into a directory tree that mirrors your PHP namespaces. There's no flat-output mode, and no setting to turn this off. Modular and domain-driven apps, such as those built with [InterNACHI/modular](https://github.com/InterNACHI/modular), keep each module's types together, and a single-namespace app gets one `app/` tree. Models, enums, resources, form requests, broadcast events, and routes all follow the same rule.
7497
+ The package writes every TypeScript file into a directory tree that mirrors your PHP namespaces. There's no flat-output mode, and no setting to turn this off. Modular and domain-driven apps, such as those built with [InterNACHI/modular](https://github.com/InterNACHI/modular), keep each module's types together, and a single-namespace app gets one `app/` tree. Models, enums, resources, form requests, broadcast events, routes, and [composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types) all follow the same rule.
6829
7498
 
6830
7499
  ### Output Structure
6831
7500
 
@@ -7001,7 +7670,7 @@ import type { Invoice } from "@data/accounting/models";
7001
7670
  import type { InvoiceStatusType } from "@data/accounting/enums";
7002
7671
  ```
7003
7672
 
7004
- Models, enums, resources, form requests, broadcast events, and routes each write their own barrels. A route barrel re-exports each controller's default export by name, such as `export { default as PostController } from './post-controller';`, rather than using `export *`. That keeps two controllers with a method of the same name from clashing.
7673
+ Models, enums, resources, form requests, broadcast events, and routes each write their own barrels, and composed types add their modules to their namespace's barrel. A route barrel re-exports each controller's default export by name, such as `export { default as PostController } from './post-controller';`, rather than using `export *`. That keeps two controllers with a method of the same name from clashing.
7005
7674
 
7006
7675
  `ts:publish --preview=true` prints each barrel's contents under its own label, such as `Model Barrel Files:` or `Enum Barrel Files:`, next to the per-class files. A verbose run, `ts:publish -v`, lists each barrel file's path in its Extras table.
7007
7676
 
@@ -7546,7 +8215,7 @@ export type ShowPageProps = Inertia.SharedData & {
7546
8215
  These expressions are typed:
7547
8216
 
7548
8217
  - **Eloquent finders and collections**, typed from the model the chain starts at. `find()`, `first()` and `firstWhere()` are `Model | null`. `findOrFail()`, `firstOrFail()`, `sole()`, `create()`, `make()`, `firstOrCreate()`, `firstOrNew()` and `updateOrCreate()` are `Model`. `all()` and `get()` are `Model[]`. `paginate()`, `simplePaginate()` and `cursorPaginate()` are `LengthAwarePaginator<Model>`, `SimplePaginator<Model>` and `CursorPaginator<Model>`, imported from `@tolki/types`. `count()` is `number` and `exists()` is `boolean`.
7549
- - **Route-bound model parameters**: a `Post $post` parameter is `Post` wherever a prop uses it.
8218
+ - **Route-bound model parameters**: a `Post $post` parameter is `Post` wherever a prop uses it, and a relation read on it is typed by the models the relation loads, so `$post->author` is `User` and `$post->comments` is `Comment[]`.
7550
8219
  - **PHP enums**: a prop holding an enum is the enum's `{Name}Type` alias, imported from the generated [enums](https://tolki.abe.dev/ts/enums.html). That includes a bare case, such as `'status' => Status::Active`. A rename with [`#[TsEnum]`](https://tolki.abe.dev/ts/enums.html#tsenum) carries over, so `#[TsEnum(name: 'Size')] enum ShirtSize` gives you `size: SizeType`.
7551
8220
  - **`$request->user()`**, typed through your `auth` config the same way [shared data](https://tolki.abe.dev/ts/inertia.html) is, and the typed `Request` reads such as `integer()`, `boolean()`, `string()` and `url()`.
7552
8221
  - **`compact()` and `array_merge()`**: passed as the whole props argument, as in `Inertia::render('Posts/Show', compact('post', 'comments'))` or `array_merge($base, [...])`, each types the same as the array literal it builds.
@@ -7971,6 +8640,7 @@ Each stage has a config key named `{feature}.{stage}_class`, such as `models.col
7971
8640
  | `form_requests` | `FormRequestsCollector` | `FormRequestGenerator` | `FormRequestTransformer` | `FormRequestWriter` |
7972
8641
  | `broadcast_channels` | `BroadcastChannelsCollector` | none | none | `BroadcastChannelsWriter` |
7973
8642
  | `broadcast_events` | `BroadcastEventsCollector` | `BroadcastEventGenerator` | `BroadcastEventTransformer` | `BroadcastEventWriter` |
8643
+ | `class_types` | `ClassTypesCollector` | `ClassTypeGenerator` | `ClassTypeTransformer` | `ClassTypeWriter` |
7974
8644
 
7975
8645
  The classes live in the `AbeTwoThree\LaravelTsPublish\Collectors`, `Generators`, `Transformers`, and `Writers` namespaces.
7976
8646
 
@@ -8181,6 +8851,7 @@ To use a template with a different name, point the feature's template key at it.
8181
8851
  | `broadcast_events.template` | `laravel-ts-publish::broadcast-event` |
8182
8852
  | `broadcast_events.index_template` | `laravel-ts-publish::broadcast-events-index` |
8183
8853
  | `broadcast_events.echo_augmentation.template` | `laravel-ts-publish::echo-broadcast-events` |
8854
+ | `class_types.template` | `laravel-ts-publish::class-type` |
8184
8855
  | `globals.template` | `laravel-ts-publish::globals` |
8185
8856
 
8186
8857
  Inertia's `inertia-config.blade.php` and Vite env's `vite-env.blade.php` have no template key. Edit your published copies to change them.
@@ -8195,7 +8866,7 @@ To change what `ts:publish` itself does, replace one of its stages instead. See
8195
8866
 
8196
8867
  ### Analyzing a Method
8197
8868
 
8198
- `analyze()` reads what a method returns: nested arrays, conditionals, closures, and method calls. It works on any class, whether or not it's a resource. A property read or a method call is typed from the class of the value you call it on, such as `$this->author->name` or a local variable.
8869
+ `analyze()` reads what a method returns: nested arrays, conditionals, closures, and method calls. It works on any class, whether or not it's a resource. A property read or a method call is typed from the class of the value you call it on, such as `$this->author->name` or a local variable. A plain value object gets the same types a resource does for enum `->value` and `->name` reads, `(object)` and `(array)` casts, helpers that return the array you pass them, and an inherited or trait method.
8199
8870
 
8200
8871
  Laravel's conditional methods, such as `$this->when()` and `$this->whenLoaded()`, belong to `JsonResource`, so `analyze()` reads them that way only on a resource. On any other class, `$this->when()` is that class's own method. Laravel's `Conditionable::when()`, which events and other classes can use, returns the callback's result or the object itself. The package doesn't type that, so the key comes back `unknown`, as it does in a publish. A resource built around the call is the exception: `UserResource::make($this->when(…))` still comes back optional on any class, though `Conditionable::when()` always sends the key. Write such a key as a ternary, or give it a `#[TsCasts]` entry on the method with `'optional' => false`.
8201
8872
 
@@ -8322,9 +8993,9 @@ The difference can also run the other way. Where a key the method returns can't
8322
8993
 
8323
8994
  Outside those cases, `analyze()` runs the same inference that resources, broadcast events, model metadata, Inertia page props, and Inertia shared data publish from. What each of those features adds on top is on its own page, linked above.
8324
8995
 
8325
- `analyze()` and `ts:publish` both type the patterns these docs describe. Anything else, such as an expression neither can follow or [a local you reassign](https://tolki.abe.dev/ts/api-resources.html#local-variables-and-narrowing), comes back `unknown` rather than a guess.
8996
+ `analyze()` and `ts:publish` both type the patterns these docs describe, including [a local you write more than once](https://tolki.abe.dev/ts/api-resources.html#local-variables-and-narrowing). Anything else, such as an expression neither can follow or a local that a reference can write, comes back `unknown` rather than a guess.
8326
8997
 
8327
- Two cases don't widen to `unknown`. [A conditional's default that can't be typed](https://tolki.abe.dev/ts/api-resources.html#passing-a-default-argument) leaves the value's own type in place. [A ternary or `?:` arm that can't be typed is left out](https://tolki.abe.dev/ts/api-resources.html#typing-a-variable-with-var), so `$cond ? $untypable : null` publishes `null`.
8998
+ Two cases don't widen to `unknown`. [A conditional's default that can't be typed](https://tolki.abe.dev/ts/api-resources.html#passing-a-default-argument) leaves the value's own type in place. [A union member that can't be typed is left out](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union), whether it's a ternary or `?:` arm or a value that a parameter's writes join. So `$cond ? $untypable : null` publishes `null`.
8328
8999
 
8329
9000
  ### Configuration Reference
8330
9001
 
@@ -8548,6 +9219,22 @@ See [Collected Files Manifest](https://tolki.abe.dev/ts/publishing.html#collecte
8548
9219
  | `broadcast_events.echo_augmentation.output_directory` | `string` | `''` | Custom output directory for the Echo augmentation file. Empty uses `broadcast_events.output_directory`, then `output_directory` |
8549
9220
  | `broadcast_events.echo_augmentation.writer_class` | `string` | `BroadcastEventsEchoWriter` | Writes the Echo augmentation file |
8550
9221
 
9222
+ ### Class Types (`class_types.*`)
9223
+
9224
+ See [Custom Types](https://tolki.abe.dev/ts/custom-types.html#configuration) for which classes compose and when the package writes their modules. A config file published before class types existed has no `class_types` block, and every key then takes its default.
9225
+
9226
+ | Config Key | Type | Default | Description |
9227
+ | ------------------------------------ | -------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
9228
+ | `class_types.enabled` | `bool` | `true` | Compose the `#[TsType]` types a class inherits into one `{Basename}Type` interface. When `false`, each value publishes its class's nearest type |
9229
+ | `class_types.template` | `string` | `laravel-ts-publish::class-type` | Blade template for each composed type's module |
9230
+ | `class_types.additional_directories` | `array` | `[]` | Directories to scan for composed classes, whose modules are written even when no value uses them. No directory is scanned by default |
9231
+ | `class_types.included` | `array` | `[]` | Only these classes compose (empty = all) |
9232
+ | `class_types.excluded` | `array` | `[]` | These classes never compose |
9233
+ | `class_types.collector_class` | `string` | `ClassTypesCollector` | Discovers composed classes in `additional_directories` |
9234
+ | `class_types.generator_class` | `string` | `ClassTypeGenerator` | Orchestrates transforming and writing |
9235
+ | `class_types.transformer_class` | `string` | `ClassTypeTransformer` | Converts a composed class into TypeScript data |
9236
+ | `class_types.writer_class` | `string` | `ClassTypeWriter` | Writes each composed type's module |
9237
+
8551
9238
  ### Inertia (`inertia.*`)
8552
9239
 
8553
9240
  | Config Key | Type | Default | Description |