@tolki/ts 1.0.4 → 1.1.1
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 +668 -144
- package/dist/enums.d.ts +1 -1
- package/dist/enums.d.ts.map +1 -1
- package/dist/enums.js +1 -7
- package/dist/index.js +3 -16
- package/dist/routes.d.ts +4 -0
- package/dist/routes.d.ts.map +1 -1
- package/dist/routes.js +206 -258
- package/dist/vite-plugin.d.ts.map +1 -1
- package/dist/vite-plugin.js +77 -127
- package/package.json +7 -4
package/README.md
CHANGED
|
@@ -412,6 +412,8 @@ let user: app.models.User;
|
|
|
412
412
|
let status: app.enums.StatusType;
|
|
413
413
|
```
|
|
414
414
|
|
|
415
|
+
Unlike in [the enum's own file](https://tolki.abe.dev/ts/enums.html#value-key-types), an enum's name in this file, such as `app.enums.Status`, is an interface of its cases, so type an enum value as `app.enums.StatusType`.
|
|
416
|
+
|
|
415
417
|
A namespace segment of more than one word is camel-cased, because a hyphen isn't valid in a namespace name. `App\Http\Resources\ReportCards\SummaryCardResource` is `app.http.resources.reportCards.SummaryCardResource`, while its file is written under `report-cards/`. An acronym is lowered as one word, so `API` is `api` and `HTTPClient` is `httpClient`.
|
|
416
418
|
|
|
417
419
|
When two published types share a name, such as `App\Models\User` and `Crm\Models\User`, each reference from another namespace is qualified with the namespace of the class your PHP code names, such as `crm.models.User`.
|
|
@@ -560,6 +562,8 @@ export const Color = defineEnum({
|
|
|
560
562
|
|
|
561
563
|
export type ColorType = "red" | "green" | "blue";
|
|
562
564
|
export type ColorKind = "Red" | "Green" | "Blue";
|
|
565
|
+
|
|
566
|
+
export type Color = ColorType;
|
|
563
567
|
```
|
|
564
568
|
|
|
565
569
|
Each part of the file does one job:
|
|
@@ -568,7 +572,7 @@ Each part of the file does one job:
|
|
|
568
572
|
- **`backed`**: whether the PHP enum is backed. [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) responses include the same key, and [`AsEnum`](#type-reference) types it.
|
|
569
573
|
- **`hex`**: an instance method published with [`#[TsEnumMethod]`](#tsenummethod), with one value per case.
|
|
570
574
|
- **`_cases`, `_methods` and `_static`**: the lists the `@tolki/ts` functions read to build a PHP-like instance. See [Runtime Utilities](#runtime-utilities).
|
|
571
|
-
- **`ColorType` and `
|
|
575
|
+
- **`ColorType`, `ColorKind` and `Color`**: type aliases for the case values and the case names. The `Color` type is another name for `ColorType`, so `Color` is both the enum object and the type of its values. See [Value & Key Types](#value--key-types).
|
|
572
576
|
|
|
573
577
|
### Enum Attributes
|
|
574
578
|
|
|
@@ -630,6 +634,8 @@ The attribute takes these parameters:
|
|
|
630
634
|
| `description` | `string` | `''` | A JSDoc comment above the property. |
|
|
631
635
|
| `params` | `array` | `[]` | Named arguments to call the method with. See [Methods With Required Parameters](#methods-with-required-parameters). |
|
|
632
636
|
|
|
637
|
+
The method must be public. A private or protected method with the attribute isn't published, and `ts:publish` warns about it.
|
|
638
|
+
|
|
633
639
|
##### Methods With Required Parameters
|
|
634
640
|
|
|
635
641
|
A method with required parameters is skipped by default, instead of publishing misleading `null` values. To include one, pass `params`. The package calls the method once per case, with those values as named arguments:
|
|
@@ -692,7 +698,7 @@ export const Status = defineEnum({
|
|
|
692
698
|
} as const);
|
|
693
699
|
```
|
|
694
700
|
|
|
695
|
-
|
|
701
|
+
The same rules apply as with `#[TsEnumMethod]`: the method must be public, and a method with required parameters is skipped unless you pass `params`.
|
|
696
702
|
|
|
697
703
|
#### `#[TsEnum]`
|
|
698
704
|
|
|
@@ -721,6 +727,8 @@ export const UserStatus = defineEnum({
|
|
|
721
727
|
|
|
722
728
|
export type UserStatusType = "active" | "inactive";
|
|
723
729
|
export type UserStatusKind = "Active" | "Inactive";
|
|
730
|
+
|
|
731
|
+
export type UserStatus = UserStatusType;
|
|
724
732
|
```
|
|
725
733
|
|
|
726
734
|
The file takes the new name too (`user-status.ts`), and models that use the enum refer to it as `UserStatusType`. The attribute takes these parameters:
|
|
@@ -730,7 +738,7 @@ The file takes the new name too (`user-status.ts`), and models that use the enum
|
|
|
730
738
|
| `name` | `string` | The TypeScript const name. Use it when two enums in one namespace publish the same name, or when a [route file](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be) uses two same-named enums from different namespaces. |
|
|
731
739
|
| `description` | `string` | A JSDoc comment. It takes priority over any PHPDoc description. |
|
|
732
740
|
|
|
733
|
-
|
|
741
|
+
When two classes in one namespace publish the same name, their barrel file and the global declaration file can't export both. For example, an enum `Role` publishes the type `RoleType`, so a second enum named `RoleType` in the same namespace clashes with it. `ts:publish` warns about any such pair, whether the classes are enums, models, resources, form requests, broadcast events or [composed types](https://tolki.abe.dev/ts/custom-types.html#composed-types). Move one of them to a namespace of its own, or rename it. An enum takes a new name with `#[TsEnum]`. In two different namespaces the pair is fine, because a file that imports both gets an alias for one. Two kinds of class in one directory, such as an enum `App\Models\Status` beside the models, drop each other's barrel exports, so keep each kind of class in a namespace of its own.
|
|
734
742
|
|
|
735
743
|
#### `#[TsCase]`
|
|
736
744
|
|
|
@@ -761,8 +769,12 @@ export const Status = defineEnum({
|
|
|
761
769
|
|
|
762
770
|
export type StatusType = "enabled" | "disabled";
|
|
763
771
|
export type StatusKind = "Enabled" | "Disabled";
|
|
772
|
+
|
|
773
|
+
export type Status = StatusType;
|
|
764
774
|
```
|
|
765
775
|
|
|
776
|
+
A published [instance method](#tsenummethod) keys its values by the new case names too. `Status.from("enabled")` resolves each method to its value for `Status::Active`, and [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) sends the same values.
|
|
777
|
+
|
|
766
778
|
The attribute takes these parameters:
|
|
767
779
|
|
|
768
780
|
| Parameter | Type | Description |
|
|
@@ -782,6 +794,8 @@ export type StatusType = "active" | "inactive";
|
|
|
782
794
|
export type StatusKind = "Active" | "Inactive"; // backed enums only
|
|
783
795
|
```
|
|
784
796
|
|
|
797
|
+
An enum with no cases publishes `never` for each alias.
|
|
798
|
+
|
|
785
799
|
Use the aliases to type a raw value or a case name:
|
|
786
800
|
|
|
787
801
|
```typescript
|
|
@@ -791,9 +805,23 @@ function setStatus(status: StatusType) {} // only 'active' | 'inactive'
|
|
|
791
805
|
function setStatusByKey(status: StatusKind) {} // only 'Active' | 'Inactive'
|
|
792
806
|
```
|
|
793
807
|
|
|
808
|
+
The enum's own name is also a type, an alias of its `{Name}Type`, so for a unit enum it's the union of its case names. One import gives you the enum object and the type of its values, as a native TypeScript `enum` does:
|
|
809
|
+
|
|
810
|
+
```typescript
|
|
811
|
+
import { Color } from "@js/types/data/app/enums";
|
|
812
|
+
|
|
813
|
+
let color: Color = Color.Red; // only 'red' | 'green' | 'blue'
|
|
814
|
+
|
|
815
|
+
Color.from(color).hex; // '#EF4444'
|
|
816
|
+
```
|
|
817
|
+
|
|
818
|
+
Use `import type { Color }` when you need only the type. Every enum file has this alias, with or without metadata and the `defineEnum()` wrapper.
|
|
819
|
+
|
|
820
|
+
To list the values or the names at runtime, call [`values`](#values) or [`keys`](#keys).
|
|
821
|
+
|
|
794
822
|
#### Reading `->value` and `->name`
|
|
795
823
|
|
|
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`:
|
|
824
|
+
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, or the case's own value when you name the case. 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
825
|
|
|
798
826
|
```php
|
|
799
827
|
enum PostStatus: int
|
|
@@ -814,7 +842,7 @@ public function toArray(Request $request): array
|
|
|
814
842
|
}
|
|
815
843
|
```
|
|
816
844
|
|
|
817
|
-
Each property publishes
|
|
845
|
+
Each property publishes what PHP can send for it:
|
|
818
846
|
|
|
819
847
|
```typescript
|
|
820
848
|
import type {
|
|
@@ -827,22 +855,41 @@ export interface PostSummaryResource {
|
|
|
827
855
|
status: PostStatusType;
|
|
828
856
|
status_name: PostStatusKind;
|
|
829
857
|
visibility: VisibilityType;
|
|
830
|
-
published:
|
|
858
|
+
published: 1;
|
|
831
859
|
}
|
|
832
860
|
```
|
|
833
861
|
|
|
834
862
|
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
863
|
|
|
836
|
-
`PostStatus::Published->value` and `PostStatus::from($value)->value`
|
|
864
|
+
A case you write out can send only its own value, so it publishes that value: `PostStatus::Published->value` publishes `1`, and `PostStatus::Published->name` publishes `'Published'`. A ternary between two cases publishes both values. Beside a read of the same enum, the alias already holds a case's value, so the value is left out: `$draft ? PostStatus::Draft->value : $this->status->value` publishes `PostStatusType`, not `0 | PostStatusType`. `PostStatus::from($value)->value` publishes `PostStatusType`, and after `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
|
|
865
|
+
|
|
866
|
+
A `->value` or `->name` read off a method call, `$this->m()`, `$this::m()`, `self::m()`, `static::m()` or `parent::m()`, publishes the value or name of each case that method returns, when neither its return type nor a `@return` tag names a class, as with no return type or `mixed`. When `draft(): mixed` returns `PostStatus::Draft`, `$this->draft()->value` publishes `0`. A method declared `: PostStatus`, or documented `@return PostStatus`, keeps the alias, so the read publishes `PostStatusType`. A `null` the method returns is left out, as it is for any `->` read, so `->value` off a method returning `$draft ? PostStatus::Draft : null` publishes `0`, and `?->value` publishes `0 | null`. A method with no return type that can end without returning a value leaves the read `unknown`.
|
|
867
|
+
|
|
868
|
+
In an API resource, `PostStatus::cases()` publishes a list of the alias. A map over the cases publishes what its callback reads from each case, with or without a type hint:
|
|
869
|
+
|
|
870
|
+
```php
|
|
871
|
+
'statuses' => PostStatus::cases(),
|
|
872
|
+
'values' => array_map(fn ($case) => $case->value, PostStatus::cases()),
|
|
873
|
+
'names' => collect(PostStatus::cases())
|
|
874
|
+
->map(fn (PostStatus $case) => $case->name)
|
|
875
|
+
->all(),
|
|
876
|
+
```
|
|
877
|
+
|
|
878
|
+
Each key publishes a list:
|
|
879
|
+
|
|
880
|
+
```typescript
|
|
881
|
+
statuses: PostStatusType[];
|
|
882
|
+
values: PostStatusType[];
|
|
883
|
+
names: PostStatusKind[];
|
|
884
|
+
```
|
|
885
|
+
|
|
886
|
+
`array_column(PostStatus::cases(), 'value')` publishes `unknown`, so map the cases instead.
|
|
837
887
|
|
|
838
888
|
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
889
|
|
|
840
890
|
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
891
|
|
|
842
|
-
|
|
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.
|
|
892
|
+
As in a resource, two enums with the same class name, such as `App\Enums\Status` and `App\Crm\Enums\Status`, are imported under aliases in a [route file](https://tolki.abe.dev/ts/routing.html), the [Inertia shared data](https://tolki.abe.dev/ts/inertia.html) file and a [model metadata](https://tolki.abe.dev/ts/model-metadata.html) companion, as in `StatusKind as CrmStatusKind`.
|
|
846
893
|
|
|
847
894
|
### Metadata & the `defineEnum()` Wrapper
|
|
848
895
|
|
|
@@ -855,7 +902,7 @@ const instance = Status.from("active");
|
|
|
855
902
|
// { name: 'Active', value: 'active', backed: true, label: 'Active User', options: [...] }
|
|
856
903
|
```
|
|
857
904
|
|
|
858
|
-
An instance method resolves to its value for the matched case (`label`), and a static method passes through as it is (`options`). See [Runtime Utilities](#runtime-utilities) for every function.
|
|
905
|
+
An instance method resolves to its value for the matched case (`label`), and a static method passes through as it is (`options`). See [Runtime Utilities](#runtime-utilities) for every function. [`values`](#values) and [`keys`](#keys) read `_cases` too.
|
|
859
906
|
|
|
860
907
|
#### Disabling Metadata or the `@tolki/ts` Wrapper
|
|
861
908
|
|
|
@@ -935,9 +982,9 @@ Enums use the same include and exclude settings as models, resources and the oth
|
|
|
935
982
|
|
|
936
983
|
### Runtime Utilities
|
|
937
984
|
|
|
938
|
-
`@tolki/ts` exports these functions
|
|
985
|
+
`@tolki/ts` exports these functions. `from`, `tryFrom` and `cases` give `defineEnum()` its PHP-like behavior, and you normally call them through the published enum (`Status.from(...)`). `values` and `keys` aren't bound to the enum, so you import them.
|
|
939
986
|
|
|
940
|
-
[cases](#cases) [defineEnum](#defineenum) [from](#from) [tryFrom](#tryfrom)
|
|
987
|
+
[cases](#cases) [defineEnum](#defineenum) [from](#from) [keys](#keys) [tryFrom](#tryfrom) [values](#values)
|
|
941
988
|
|
|
942
989
|
#### `cases`
|
|
943
990
|
|
|
@@ -982,6 +1029,19 @@ const result = from(Status, "active");
|
|
|
982
1029
|
from(Status, "non-valid-key"); // throws
|
|
983
1030
|
```
|
|
984
1031
|
|
|
1032
|
+
#### `keys`
|
|
1033
|
+
|
|
1034
|
+
Like `array_column(Color::cases(), 'name')` in PHP, `keys` returns the enum's case names in case order, typed as a union of those names:
|
|
1035
|
+
|
|
1036
|
+
```typescript
|
|
1037
|
+
import { keys } from "@tolki/ts";
|
|
1038
|
+
import { Color } from "@js/types/data/app/enums";
|
|
1039
|
+
|
|
1040
|
+
keys(Color); // ['Red', 'Green', 'Blue']
|
|
1041
|
+
```
|
|
1042
|
+
|
|
1043
|
+
Like `values`, `keys` reads the `_cases` list and returns an empty array without `enums.metadata_enabled`.
|
|
1044
|
+
|
|
985
1045
|
#### `tryFrom`
|
|
986
1046
|
|
|
987
1047
|
Like PHP's [tryFrom](https://www.php.net/manual/en/backedenum.tryfrom.php), `tryFrom` works like `from` but returns `null` for a value that matches no case:
|
|
@@ -994,6 +1054,37 @@ const result = tryFrom(Status, "active");
|
|
|
994
1054
|
const missing = tryFrom(Status, "non-valid-key"); // null
|
|
995
1055
|
```
|
|
996
1056
|
|
|
1057
|
+
#### `values`
|
|
1058
|
+
|
|
1059
|
+
Like `array_column(Color::cases(), 'value')` in PHP, `values` returns the enum's case values in case order, typed as its `{Name}Type` union:
|
|
1060
|
+
|
|
1061
|
+
```typescript
|
|
1062
|
+
import { values } from "@tolki/ts";
|
|
1063
|
+
import { Color } from "@js/types/data/app/enums";
|
|
1064
|
+
|
|
1065
|
+
values(Color); // ['red', 'green', 'blue']
|
|
1066
|
+
```
|
|
1067
|
+
|
|
1068
|
+
A unit enum publishes each case name as its value, so `values` returns its case names. PHP's `array_column()` returns an empty array for a unit enum.
|
|
1069
|
+
|
|
1070
|
+
`values` and `keys` read the `_cases` list, so they need `enums.metadata_enabled` and return an empty array without it. `defineEnum()` doesn't add `values` or `keys` to the enum. An enum that publishes its own `values()` or `keys()` static method keeps that published value under the name, so `Status.values` is the static method's published output while `values(Status)` returns the case values.
|
|
1071
|
+
|
|
1072
|
+
### Bundling
|
|
1073
|
+
|
|
1074
|
+
An enum nobody uses drops out of your bundle in Vite (Rolldown), Rollup, webpack and Rspack, because `defineEnum` and the other runtime utilities are marked as free of side effects, except `from`, which throws on an unknown value and is always kept.
|
|
1075
|
+
|
|
1076
|
+
esbuild doesn't follow that mark across files, so it keeps the call unless the call site says it is safe to remove:
|
|
1077
|
+
|
|
1078
|
+
```typescript
|
|
1079
|
+
export const Status = /* @__PURE__ */ defineEnum({
|
|
1080
|
+
Active: "active",
|
|
1081
|
+
Inactive: "inactive",
|
|
1082
|
+
_cases: ["Active", "Inactive"],
|
|
1083
|
+
});
|
|
1084
|
+
```
|
|
1085
|
+
|
|
1086
|
+
Rspack also needs the call-site form when the same module derives a list from the enum, such as `export const STATUSES = /* @__PURE__ */ values(Status)`. [Bundling and Tree-Shaking](https://tolki.abe.dev/tree-shaking.html) lists every bundler.
|
|
1087
|
+
|
|
997
1088
|
### Vite Plugin
|
|
998
1089
|
|
|
999
1090
|
The `@tolki/ts` package ships a Vite plugin that republishes enums and routes automatically during development. See the [Vite Plugin documentation](https://tolki.abe.dev/ts/vite-plugin.html).
|
|
@@ -1010,6 +1101,7 @@ The runtime functions come from `@tolki/ts`. The types come from `@tolki/types`,
|
|
|
1010
1101
|
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1011
1102
|
| `defineEnum()` | Wraps a raw enum const with bound `from`, `tryFrom` and `cases` helpers. |
|
|
1012
1103
|
| `from()`, `tryFrom()`, `cases()` | Standalone versions that take the enum object as their first argument. |
|
|
1104
|
+
| `values()`, `keys()` | The case values, or the case names, in case order. |
|
|
1013
1105
|
| `EnumConst` | The base shape every generated enum const satisfies. |
|
|
1014
1106
|
| `CaseKeys<T>` / `CaseValue<T>` | The union of case key names, or of case values, for an enum const. |
|
|
1015
1107
|
| `MethodKeys<T>` / `StaticKeys<T>` | The union of instance method key names, or of static method key names. |
|
|
@@ -1387,7 +1479,7 @@ Most columns and accessors type themselves. When one publishes `unknown` or `unk
|
|
|
1387
1479
|
2. A class-level `@property` or `@property-read` tag, including one that uses a `@phpstan-type` or `@phpstan-import-type` alias.
|
|
1388
1480
|
3. A `@return MorphTo<A|B, $this>` generic on a `morphTo()` relation.
|
|
1389
1481
|
|
|
1390
|
-
PHPStan and Larastan read all of them, so the annotation that fixes your TypeScript is also checked by static analysis, and the package reads them with no configuration. `#[TsCasts]` is still the right tool when a shape's keys are built at runtime, or when the type belongs to the frontend and needs its own import. The [Annotation Checklist](#annotation-checklist) lists each case by symptom.
|
|
1482
|
+
PHPStan and Larastan read all of them, so the annotation that fixes your TypeScript is also checked by static analysis, and the package reads them with no configuration. When a docblock has more than one tag of a kind, the package reads them in PHPStan's order: `@phpstan-return`, then `@psalm-return`, then `@return`, and the same for `@var`, `@param`, `@property` and `@use`. A prefixed tag that's vague, such as `@phpstan-return array<string, mixed>`, yields to a precise plain tag. `#[TsCasts]` is still the right tool when a shape's keys are built at runtime, or when the type belongs to the frontend and needs its own import. The [Annotation Checklist](#annotation-checklist) lists each case by symptom.
|
|
1391
1483
|
|
|
1392
1484
|
#### Accessor Getter Bodies
|
|
1393
1485
|
|
|
@@ -1427,7 +1519,7 @@ export interface ReleaseMutators {
|
|
|
1427
1519
|
}
|
|
1428
1520
|
```
|
|
1429
1521
|
|
|
1430
|
-
The package reads `Attribute::make()`, `Attribute::get()`, `new Attribute(get: ...)` and old-style `get{Name}Attribute()` bodies. An accessor declared in a trait is read against the model that uses the trait. A method the getter calls is read the same way: `channelOptions()` returns `static::channelLabels()`, whose signature is a bare `: array`, and still publishes `{ "1": string; "2": string }`. A getter that returns an untyped property is typed from the property's default
|
|
1522
|
+
The package reads `Attribute::make()`, `Attribute::get()`, `new Attribute(get: ...)` and old-style `get{Name}Attribute()` bodies. An accessor declared in a trait is read against the model that uses the trait. A method the getter calls is read the same way: `channelOptions()` returns `static::channelLabels()`, whose signature is a bare `: array`, and still publishes `{ "1": string; "2": string }`. A getter that returns an untyped property is typed from the property's default joined with what the class and its children write to it, so `channels()`, which returns `protected $allowedChannels`, publishes `string[]` when nothing writes it.
|
|
1431
1523
|
|
|
1432
1524
|
A specific return type or `Attribute<Get, Set>` generic is always read first, so the getter body never overrides an accurate annotation. When the getter can't be typed, the accessor keeps the type from its signature or docblock, or publishes `unknown` if it has neither. That happens when the getter:
|
|
1433
1525
|
|
|
@@ -1441,9 +1533,15 @@ A specific return type or `Attribute<Get, Set>` generic is always read first, so
|
|
|
1441
1533
|
|
|
1442
1534
|
The `null` case keeps a getter from publishing a type that's plainly wrong: `fn ($value, array $attributes) => $attributes['title'] ?? null` publishes `unknown`, not `null`, because its real value is the title.
|
|
1443
1535
|
|
|
1536
|
+
A getter closure with no native return type takes its type from a `@return` docblock written just before it, so `Attribute::get(/** @return int */ fn () => json_decode($this->stats_json))` publishes `number`. The package reads that docblock only when it can't type what the getter returns, and ignores a vague one, such as `@return mixed`.
|
|
1537
|
+
|
|
1538
|
+
A getter that reads an attribute through `getAttribute()` or `getAttributeValue()` with a literal name takes the attribute's type, so `Attribute::get(fn () => $this->getAttribute('title'))` publishes `string`, as `fn () => $this->title` does.
|
|
1539
|
+
|
|
1540
|
+
Laravel runs an accessor's getter for a `NULL` column too, so an accessor on a nullable column publishes `| null` only where its getter can return `null`. A getter whose native return type is non-null, such as `fn (?string $value): array => …`, publishes no `| null`. One whose native return type allows `null`, such as `: ?array`, always publishes it, even when its `Attribute<…>` docblock leaves the `null` out.
|
|
1541
|
+
|
|
1444
1542
|
#### Typing `array` Casts With `@property`
|
|
1445
1543
|
|
|
1446
|
-
A column cast to `'array'`, or to any cast with no more specific type, publishes as `unknown[]`. Instead of `#[TsCasts]`, add a class-level `@property` or `@property-read` tag with the real shape. It's the same tag PHPStan and Larastan read:
|
|
1544
|
+
A column cast to `'array'`, or to any cast with no more specific type, publishes as `unknown[]`. Laravel sends the decoded JSON as it is, so a column holding an object, such as `{"theme":"dark"}`, is sent as that object, which `unknown[]` doesn't describe. The same holds for `collection` and `AsCollection` casts. Instead of `#[TsCasts]`, add a class-level `@property` or `@property-read` tag with the real shape. It's the same tag PHPStan and Larastan read:
|
|
1447
1545
|
|
|
1448
1546
|
```php
|
|
1449
1547
|
/**
|
|
@@ -1463,7 +1561,7 @@ A tag applies only when the column's own type is vague. It never overrides a spe
|
|
|
1463
1561
|
|
|
1464
1562
|
A tag that is still partly vague is used when it's more specific than the type it replaces. `@property array<string, mixed>|null $settings` turns a plain `'array'` cast into `Record<string, unknown> | null`: the type still names `unknown`, but it beats `unknown[] | null`. A tag that is exactly as vague as the original is ignored: `unknown`, `unknown[]`, `object`, or the `unknown[] | Record<string, unknown>` of a bare collection.
|
|
1465
1563
|
|
|
1466
|
-
The package also reads `@property` tags on the traits the model and its parents use, and on the traits those traits use. A trait that supplies an accessor can document it that way. The `$`-less form some packages use, `@property string[] labels`, works as long as nothing follows the property name.
|
|
1564
|
+
The package also reads `@property` tags on the traits the model and its parents use, and on the traits those traits use. A trait that supplies an accessor can document it that way. A class a trait's docblocks name resolves through the trait file's imports, not the model's, and so does the `@var` of a property the trait declares. The `$`-less form some packages use, `@property string[] labels`, works as long as nothing follows the property name.
|
|
1467
1565
|
|
|
1468
1566
|
#### Typing JSON Columns With `@phpstan-type` Aliases
|
|
1469
1567
|
|
|
@@ -1538,16 +1636,18 @@ A docblock intersection resolves each member and joins them with `&`:
|
|
|
1538
1636
|
protected function assignedUsers(): Attribute
|
|
1539
1637
|
```
|
|
1540
1638
|
|
|
1541
|
-
|
|
1639
|
+
Both classes keep their types, and the file imports both:
|
|
1542
1640
|
|
|
1543
1641
|
```typescript
|
|
1642
|
+
import type { TaskAssignment, User } from ".";
|
|
1643
|
+
|
|
1544
1644
|
export interface ProjectMutators {
|
|
1545
|
-
assigned_users: (User & { pivot:
|
|
1645
|
+
assigned_users: (User & { pivot: TaskAssignment })[];
|
|
1546
1646
|
// …
|
|
1547
1647
|
}
|
|
1548
1648
|
```
|
|
1549
1649
|
|
|
1550
|
-
A
|
|
1650
|
+
A model or an enum inside a docblock shape keeps its type at any depth, as `TaskAssignment` does here. Two kinds of shape publish each model and enum in them as `unknown`: one that also names another class, such as an API resource, and one that spells a class's name as a string literal or a key, as in `array{kind: 'User', owner: User}`. A member that can't be resolved is dropped from the intersection, instead of turning the whole type into `unknown`, since `A & B` is assignable to `A`.
|
|
1551
1651
|
|
|
1552
1652
|
#### Trait `@template` Bindings
|
|
1553
1653
|
|
|
@@ -1577,11 +1677,19 @@ export interface ProjectMutators {
|
|
|
1577
1677
|
}
|
|
1578
1678
|
```
|
|
1579
1679
|
|
|
1580
|
-
PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too.
|
|
1680
|
+
PHPStan reads the `@use` tag for the same purpose, so static analysis checks the binding too. The trait's name in the tag resolves through the file's imports, then the model's namespace, so a trait declared beside the model needs no `use` import.
|
|
1581
1681
|
|
|
1582
1682
|
#### Custom Cast Classes
|
|
1583
1683
|
|
|
1584
|
-
A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes the return type of its `get()` method.
|
|
1684
|
+
A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes the return type of its `get()` method. When the cast class has a `serialize()` method, including one a `Castable` value object names, Laravel sends what `serialize()` returns when it converts the model to JSON, with or without the `SerializesCastableAttributes` interface. The column then publishes:
|
|
1685
|
+
|
|
1686
|
+
- **No declared type, or `mixed`**: the type its `return` statements prove, so `return (string) $value;` publishes `string`. Where they prove none, the column keeps `get()`'s type, except a `mixed` `serialize()` on a cast that implements the interface, which publishes `unknown | null`.
|
|
1687
|
+
- **A bare `array` or `object`, on a cast without the interface**: `get()`'s type, where `get()` returns a value object or an array shape. `?object` and `array|object` work the same way. Over a scalar `get()`, a bare `array` publishes `unknown[] | Record<string, unknown>`.
|
|
1688
|
+
- **Any other declared type**: that type, such as `string`.
|
|
1689
|
+
|
|
1690
|
+
Laravel calls `get()` for a `NULL` column too, so a nullable column cast to a class whose `get()` declares a non-null return type publishes no `| null`. For a `coordinate_data` column that may be `NULL`, cast with a `get()` that always returns a `Coordinate`, the model publishes `coordinate_data: { lat: number; lng: number }`. Laravel sends a `null` from `get()` without calling `serialize()`, so on a nullable column, a `get()` that declares a nullable return type, or returns `null` itself, adds `| null` to the `serialize()` type.
|
|
1691
|
+
|
|
1692
|
+
A `NOT NULL` column never holds a `NULL`, so it publishes the `serialize()` type alone. With a cast whose `get()` returns `?CarbonImmutable` and whose `serialize()` returns `string`, a `NOT NULL` `opens_at` column publishes `opens_at: string`, and a nullable `closes_at` column publishes `closes_at: string | null`. A `Castable` that names the cast publishes the same way, and a `null` that `serialize()` itself declares or returns stays on either column. A `get()` that turns a stored value into `null`, such as an empty string, still sends that `null` from a `NOT NULL` column, which the type leaves out. Type such a column with [`#[TsCasts]`](#tscasts).
|
|
1585
1693
|
|
|
1586
1694
|
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
1695
|
|
|
@@ -1689,7 +1797,9 @@ final readonly class ShippingOptions implements Arrayable
|
|
|
1689
1797
|
}
|
|
1690
1798
|
```
|
|
1691
1799
|
|
|
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
|
|
1800
|
+
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 an enum or a published model publishes that type, and the file imports it, so `public Status $status` publishes `status: StatusType`. A property whose class has or inherits a [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html) publishes that type, with its import.
|
|
1801
|
+
|
|
1802
|
+
A promoted property with no `@var` takes its type from the constructor's `@param`, as PHPStan reads it. So a constructor documented `@param list<string> $stops` publishes its promoted `public array $stops` as `stops: string[]` instead of `unknown[]`.
|
|
1693
1803
|
|
|
1694
1804
|
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.
|
|
1695
1805
|
|
|
@@ -1756,7 +1866,7 @@ A column or accessor typed as a backed or unit enum publishes in two ways:
|
|
|
1756
1866
|
- **The main interface**: `User` uses the enum's `{Enum}Type` union, which is how Laravel serializes the enum when it converts a model to JSON.
|
|
1757
1867
|
- **A parallel `Resource` interface**: `{Model}Resource` types the same property as [`AsEnum<typeof Enum>`](https://tolki.abe.dev/ts/enums.html#type-reference), and the split template adds `{Model}MutatorsResource` for accessors and `{Model}AllResource`. `AsEnum` is the shape you get once the raw value is a full enum instance, either from `Status.from(user.status)` or from an API resource that serialized the enum with [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html).
|
|
1758
1868
|
|
|
1759
|
-
A property is rewritten only when its type is a single enum or a list of one, either optionally `| null`. A list becomes `AsEnum<typeof Enum>[]`. A shape, or a union with other types, keeps its own type.
|
|
1869
|
+
A property is rewritten only when its type is a single enum or a list of one, either optionally `| null`. A list becomes `AsEnum<typeof Enum>[]`. A shape, or a union with other types, keeps its own type. An accessor that returns an enum's `->value` or `->name` keeps the enum's alias in `{Model}Resource` and `{Model}MutatorsResource`, because it sends the scalar, not the enum. Only an accessor that returns the enum itself takes `AsEnum<typeof Enum>`.
|
|
1760
1870
|
|
|
1761
1871
|
This helper resolves the raw `role` value into the type `UserResource` declares:
|
|
1762
1872
|
|
|
@@ -1855,11 +1965,11 @@ The `unknown[]` collection row is the bare form. `AsEnumCollection::of(...)`, `A
|
|
|
1855
1965
|
|
|
1856
1966
|
A parameterized docblock generic in `@return`, `@property` or `Attribute<>` publishes a more specific type, based on its key type. Every container behaves the same way for a given key type:
|
|
1857
1967
|
|
|
1858
|
-
| Key type
|
|
1859
|
-
|
|
|
1860
|
-
| `int`, or omitted
|
|
1861
|
-
| `string`
|
|
1862
|
-
| `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1968
|
+
| Key type | Emitted | Containers |
|
|
1969
|
+
| ----------------------------------- | -------------------------- | ----------------------------------------------------- |
|
|
1970
|
+
| `int`, or omitted | `X[]` | `list<X>`, `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1971
|
+
| `string` | `Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1972
|
+
| `int\|string`, `array-key`, `mixed` | `X[] \| Record<string, X>` | `array<…>`, `iterable<…>`, `Collection<…>` |
|
|
1863
1973
|
|
|
1864
1974
|
`list<X>` has no key type, so it always publishes as `X[]`. A container with no generic at all, such as a bare `Collection`, uses the [Arrays & Objects](#arrays--objects) table above instead.
|
|
1865
1975
|
|
|
@@ -2110,14 +2220,14 @@ Each returned key's TypeScript type comes from the first of these that applies:
|
|
|
2110
2220
|
3. **The method body**: the package reads the returned array literal, with `$model` typed as its declared class. These need no annotation:
|
|
2111
2221
|
- Scalars, casts such as `(string) …`, and nested inline arrays
|
|
2112
2222
|
- Calls on `$model` whose Laravel signature or docblock declares a return type, such as `getTable()`, `getKeyName()`, `getRouteKeyName()` and `getMorphClass()`, which all publish as `string`
|
|
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
|
|
2223
|
+
- 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. Two enums with the same class name are imported under aliases, such as `StatusType as CrmStatusType`, and so are their `{Name}Kind` aliases
|
|
2114
2224
|
- 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`
|
|
2115
2225
|
|
|
2116
2226
|
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).
|
|
2117
2227
|
|
|
2118
2228
|
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.
|
|
2119
2229
|
|
|
2120
|
-
Two kinds of value
|
|
2230
|
+
An enum named in the docblock is imported from the generated enums, at any depth, so `pair: array{role: Role}` publishes `pair: { role: RoleType }`. So is one named in a `#[TsCasts]` entry with no `import`, when the key's value holds that enum. Two kinds of value still need a `#[TsCasts]` entry with an `import`. The first is any other class the docblock names at any depth, such as a model or an API resource, because a docblock string carries no import path. The second is a model or a resource the method body returns, because a metadata value doesn't have to match either interface, so the package never imports one for it. Without the entry, the companion fails, and the error names the model, the key and its type.
|
|
2121
2231
|
|
|
2122
2232
|
Every returned key must end up with a type, and every required key must be returned. Otherwise the companion fails, and the error names the model and the keys.
|
|
2123
2233
|
|
|
@@ -2294,8 +2404,8 @@ export interface WarehouseResource {
|
|
|
2294
2404
|
The package types most properties from the resource's backing Eloquent model, using its database columns, casts, accessors, and relations. It looks for that model in this order:
|
|
2295
2405
|
|
|
2296
2406
|
1. The `#[TsResource(model: User::class)]` attribute.
|
|
2297
|
-
2. A `@mixin
|
|
2298
|
-
3. The nearest parent class whose docblock has
|
|
2407
|
+
2. A `@mixin`, `@extends`, or `@property … $resource` tag in the resource's own docblock. The class name resolves through the file's `use` imports.
|
|
2408
|
+
3. The nearest parent class whose docblock has one of those tags.
|
|
2299
2409
|
4. A `$resource` property redeclared with a `@var` type, such as `/** @var User */ public $resource;`.
|
|
2300
2410
|
5. Laravel's naming convention in reverse, so `App\Http\Resources\UserResource` maps to `App\Models\User`.
|
|
2301
2411
|
6. A model whose `#[UseResource(UserResource::class)]` attribute names the resource. This attribute needs Laravel 12.29 or later.
|
|
@@ -2306,10 +2416,49 @@ Step 3 lets a subclass use its parent's model without repeating the docblock, wh
|
|
|
2306
2416
|
|
|
2307
2417
|
If no model resolves, a property read from the model, such as `$this->id`, publishes `unknown`.
|
|
2308
2418
|
|
|
2309
|
-
`$this->resource` holds the backing model, so a key that returns it whole publishes the model's interface. `'post' => $this->resource` publishes `post: Post`. If the resource
|
|
2419
|
+
`$this->resource` holds the backing model, so a key that returns it whole publishes the model's interface. `'post' => $this->resource` publishes `post: Post`. If the resource declares `$resource` as nullable, such as `/** @var Post|null */ public $resource;`, `?Post`, or `@extends JsonResource<Post|null>`, the key keeps that `null`: `post: Post | null`.
|
|
2310
2420
|
|
|
2311
2421
|
A `ResourceCollection` is backed by no model, whatever its docblock or `#[TsResource(model:)]` names, because its `$this->resource` holds the collected items. A model read in a collection, such as `$this->title`, publishes `unknown`. See [Reading `$this->resource`](#reading-this-resource).
|
|
2312
2422
|
|
|
2423
|
+
#### Resources That Wrap Other Classes
|
|
2424
|
+
|
|
2425
|
+
A resource can wrap a class that isn't a model, such as a value object. Name the class in an `@extends JsonResource<X>`, `@mixin X`, or `@property X $resource` tag, or redeclare `$resource` with `@var X`. Reads through `$this->resource` and through the resource itself then take the types that class declares:
|
|
2426
|
+
|
|
2427
|
+
```php
|
|
2428
|
+
/**
|
|
2429
|
+
* @extends JsonResource<PostStats>
|
|
2430
|
+
*/
|
|
2431
|
+
class StatsSummaryResource extends JsonResource
|
|
2432
|
+
{
|
|
2433
|
+
public function toArray(Request $request): array
|
|
2434
|
+
{
|
|
2435
|
+
return [
|
|
2436
|
+
'views' => $this->resource->views,
|
|
2437
|
+
'shares' => $this->shares,
|
|
2438
|
+
'summary' => $this->summary(),
|
|
2439
|
+
];
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
```
|
|
2443
|
+
|
|
2444
|
+
`PostStats` declares `public float $views`, `public int $shares`, and `summary(): string`, so the resource publishes:
|
|
2445
|
+
|
|
2446
|
+
```typescript
|
|
2447
|
+
export interface StatsSummaryResource {
|
|
2448
|
+
views: number;
|
|
2449
|
+
shares: number;
|
|
2450
|
+
summary: string;
|
|
2451
|
+
}
|
|
2452
|
+
```
|
|
2453
|
+
|
|
2454
|
+
A tag that names a class other than a model stops the naming-convention and `#[UseResource]` guesses, because the resource doesn't wrap a model. The guess stands only when the guessed model is an instance of the class the tag names, such as `@mixin Arrayable`, an interface every model implements. `#[TsResource(model:)]` always wins over the tag.
|
|
2455
|
+
|
|
2456
|
+
A tag that names no class the package can load, such as an IDE helper's `@mixin IdeHelperPost`, is skipped, and so is one that names `Model` itself or the `Eloquent` alias. The model the other steps find still applies.
|
|
2457
|
+
|
|
2458
|
+
A tag can also name an intersection of a model and an interface it implements. With `@extends JsonResource<Post&HasLabel>`, `$this->title` reads the `Post` column and `$this->label()` reads the method `HasLabel` declares, so both publish `string`.
|
|
2459
|
+
|
|
2460
|
+
A subclass that redeclares `$resource` with its own `@var` decides what an inherited `toArray()` reads, because PHP has only one `$resource` property.
|
|
2461
|
+
|
|
2313
2462
|
### Supported `toArray()` Patterns
|
|
2314
2463
|
|
|
2315
2464
|
These sections cover the Laravel resource features you use in `toArray()`. Each one shows the PHP you write and the TypeScript it produces.
|
|
@@ -2332,9 +2481,9 @@ name: string;
|
|
|
2332
2481
|
status: StatusType;
|
|
2333
2482
|
```
|
|
2334
2483
|
|
|
2335
|
-
`$this->resource->name` reads the same attribute, so it publishes the same type. A property you declare on the resource class itself, such as a promoted constructor parameter, takes its type from that declaration. It wins over a model attribute with the same name, as it does in PHP.
|
|
2484
|
+
`$this->resource->name` reads the same attribute, so it publishes the same type. A property you declare on the resource class itself, such as a promoted constructor parameter, takes its type from that declaration. It wins over a model attribute with the same name, as it does in PHP. A `@var` docblock on the property names classes through the imports of the file that declares it, so a property a trait declares uses the trait's imports. A promoted property with no `@var` takes its type from the constructor's `@param`, as PHPStan reads it.
|
|
2336
2485
|
|
|
2337
|
-
An untyped property
|
|
2486
|
+
An untyped property publishes its default's type joined with each value the resource, its parents, its traits, or its children write to it, so `protected $stage = Status::Draft;` publishes `StatusType`, and a protected or private one declared without a value, such as `protected $name;`, publishes `null`. Writes include element writes and writes inside a closure, typed by the closure's parameters and `use` imports, so `protected $sizes = ['small' => 1];` extended by `$this->sizes['large'] = 2;` publishes `{ small: number; large?: number }`. A write in a trait method the resource overrides doesn't count. The property publishes `unknown` when a write is a value from an untyped parameter, a by-reference call such as `sort($this->sizes)`, or an `unset()` of the whole property.
|
|
2338
2487
|
|
|
2339
2488
|
#### Conditional Methods
|
|
2340
2489
|
|
|
@@ -2470,7 +2619,17 @@ export interface PostResource {
|
|
|
2470
2619
|
}
|
|
2471
2620
|
```
|
|
2472
2621
|
|
|
2473
|
-
When the package can't type the value of `whenHas()` or `whenAppended()`, the property publishes `unknown`, not the attribute's type, because the value replaces the attribute in the response. `json_decode()` returns `mixed`, and a plain title decodes to `null`, so `title_unresolvable` is `unknown`. To type it, give the closure a native return type
|
|
2622
|
+
When the package can't type the value of `whenHas()` or `whenAppended()`, the property publishes `unknown`, not the attribute's type, because the value replaces the attribute in the response. `json_decode()` returns `mixed`, and a plain title decodes to `null`, so `title_unresolvable` is `unknown`. To type it, give the closure a native return type, or a `@return` docblock written just before the closure:
|
|
2623
|
+
|
|
2624
|
+
```php
|
|
2625
|
+
'title_typed' => $this->whenHas('title', fn ($title): ?string => json_decode($title)),
|
|
2626
|
+
'title_documented' => $this->whenHas('title',
|
|
2627
|
+
/** @return string|null */
|
|
2628
|
+
fn ($title) => json_decode($title),
|
|
2629
|
+
),
|
|
2630
|
+
```
|
|
2631
|
+
|
|
2632
|
+
Both properties publish `string | null`, and both stay optional. The package reads the docblock only on a closure with no native return type, and ignores a vague one, such as `@return mixed`. A docblock written before the whole call, or above the array item, describes the call's value rather than the closure, so it isn't read. To type the key itself, use [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
2474
2633
|
|
|
2475
2634
|
`whenExistsLoaded()` keeps `boolean` for a value it can't type. Without a value argument, `whenHas('phone')` types from its column, and `whenExistsLoaded('user')` publishes `boolean`.
|
|
2476
2635
|
|
|
@@ -2679,6 +2838,23 @@ visibility_from_helper: AsEnum<typeof Visibility> | null;
|
|
|
2679
2838
|
|
|
2680
2839
|
Wrapping a conditional value, as in `EnumResource::make($this->whenHas('status'))`, makes the property optional, as the conditional method alone would.
|
|
2681
2840
|
|
|
2841
|
+
`EnumResource::make(Status::tryFrom($value))` adds `| null`, because `tryFrom()` returns `null` for a value that matches no case. A `map()` that wraps each element is different: kept as a collection, it sends `[]` for an element whose enum is `null`. Laravel turns an empty `EnumResource` into `null` only inside an array, so end the chain with `->all()` to get `null` instead:
|
|
2842
|
+
|
|
2843
|
+
```php
|
|
2844
|
+
'roles' => $this->members
|
|
2845
|
+
->map(fn (User $user) => EnumResource::make($user->role)),
|
|
2846
|
+
'role_list' => $this->members
|
|
2847
|
+
->map(fn (User $user) => EnumResource::make($user->role))
|
|
2848
|
+
->all(),
|
|
2849
|
+
```
|
|
2850
|
+
|
|
2851
|
+
The two keys publish what each sends for a member with no role:
|
|
2852
|
+
|
|
2853
|
+
```typescript
|
|
2854
|
+
roles: (AsEnum<typeof Role> | never[])[];
|
|
2855
|
+
role_list: (AsEnum<typeof Role> | null)[];
|
|
2856
|
+
```
|
|
2857
|
+
|
|
2682
2858
|
A ternary that wraps only one of its arms keeps both shapes. The property publishes a union, with the import each side needs, even inside an inline array:
|
|
2683
2859
|
|
|
2684
2860
|
```php
|
|
@@ -2816,7 +2992,7 @@ A closure or an arrow function in value position is typed from what it returns:
|
|
|
2816
2992
|
}),
|
|
2817
2993
|
```
|
|
2818
2994
|
|
|
2819
|
-
This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`.
|
|
2995
|
+
This works wherever a value goes, including `when()`, `whenLoaded()`, `whenNotNull()`, `merge()`, and `mergeWhen()`. When the package can't type what a closure returns, the closure's native return type types the value, and so does a `@return` docblock on a closure with no native return type, as [`whenHas()`, `whenAppended()`, and `whenExistsLoaded()`](#whenhas-whenappended-and-whenexistsloaded-type-from-the-value-you-pass) shows.
|
|
2820
2996
|
|
|
2821
2997
|
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
2998
|
|
|
@@ -2887,6 +3063,10 @@ App\Http\Resources\PostResource: The value on line 31 leaves out `$this->opaqueT
|
|
|
2887
3063
|
|
|
2888
3064
|
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
3065
|
|
|
3066
|
+
Once the value is typed, an empty `[]` beside a list publishes the list alone. With `opaqueTags()` declared `@return list<string>`, `tags` publishes `string[]`.
|
|
3067
|
+
|
|
3068
|
+
A `@return` docblock that types the key, on `toArray()` or on a method it spreads, also types the value left out. The docblock's type takes that value's place beside the values the body types. Under `score: int|string|null`, a `score` whose body types `number | null` and leaves one more value out publishes `number | null | string`. `ts:publish` prints no warning for a value the docblock types. A value it doesn't type, such as one under a `mixed` entry or under a key the docblock doesn't name, still warns. [Return Branches and `@return` Shapes](#return-branches-and-return-shapes) shows an example.
|
|
3069
|
+
|
|
2890
3070
|
`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.
|
|
2891
3071
|
|
|
2892
3072
|
### Method Calls, Variables, and Collections
|
|
@@ -2895,7 +3075,7 @@ Values you compute in `toArray()` get types too: method calls, property reads on
|
|
|
2895
3075
|
|
|
2896
3076
|
#### Method Return Types
|
|
2897
3077
|
|
|
2898
|
-
A method call takes its type from the called method's signature: its native return type, or its `@return` docblock when the native type is missing or vague. This works for calls on enum casts, date casts, models, Eloquent collections, value objects, and services resolved from the container:
|
|
3078
|
+
A method call takes its type from the called method's signature: its native return type, or its `@return` docblock when the native type is missing or vague. When a method has more than one of `@phpstan-return`, `@psalm-return`, and `@return`, the package reads them in that order, as PHPStan does, and a vague one, such as `array<string, mixed>`, yields to a precise one. This works for calls on enum casts, date casts, models, Eloquent collections, value objects, and services resolved from the container:
|
|
2899
3079
|
|
|
2900
3080
|
```php
|
|
2901
3081
|
public function toArray(Request $request): array
|
|
@@ -2929,6 +3109,8 @@ export interface PostResource {
|
|
|
2929
3109
|
|
|
2930
3110
|
A property read works the same way. Once `$post` holds a `Post`, `$post?->author?->name` publishes `string | null`. A value object's public property takes its declared type, so `$this->stats?->views` publishes `number | null`. A `?->` adds `| null` to the result once, however many steps use it.
|
|
2931
3111
|
|
|
3112
|
+
A model or an enum named in a `@return` shape keeps its type at any depth, and the file imports it. A method documented `@return array{owner: User, count: int}` publishes `{ owner: User; count: number }`, whether you call it on the resource, on a service, or statically. Two kinds of shape publish each model and enum in them as `unknown`: one that also names another class, such as an API resource, and one that spells a class's name as a string literal or a key, as in `array{kind: 'User', owner: User}`.
|
|
3113
|
+
|
|
2932
3114
|
When the declaration says too little, as with no return type, `mixed`, or a bare `array`, the method's own `return` statements set the type:
|
|
2933
3115
|
|
|
2934
3116
|
```php
|
|
@@ -2976,10 +3158,12 @@ public function total(): mixed
|
|
|
2976
3158
|
}
|
|
2977
3159
|
```
|
|
2978
3160
|
|
|
2979
|
-
`$this->resource->total()` calls the model's method directly, so it publishes the model's type. When neither the resource method's declaration nor its body types the call, the key publishes `unknown`, never the model method's type. Give the method a return type to fix it. The same holds for a
|
|
3161
|
+
`$this->resource->total()` calls the model's method directly, so it publishes the model's type. When neither the resource method's declaration nor its body types the call, the key publishes `unknown`, never the model method's type. Give the method a return type to fix it. The same holds for a resource that [wraps a class other than a model](#resources-that-wrap-other-classes), such as one declared with `@extends JsonResource<CartTotals>` or `/** @var CartTotals */ public $resource;`. If `CartTotals` doesn't declare the method you call, the key publishes `unknown`, because Laravel throws there.
|
|
2980
3162
|
|
|
2981
3163
|
Some of Laravel's own methods declare loose types, so the package reads the model instead. `getKey()` publishes the model's key type, `number` or `string`, and `modelKeys()` publishes a list of it. That's why `comment_ids` above is `number[]`. `resolveRouteBinding()` publishes the model you call it on, or `null`, so `$this->author?->resolveRouteBinding($this->user_id)` publishes `User | null`.
|
|
2982
3164
|
|
|
3165
|
+
`getAttribute()` and `getAttributeValue()` with a literal name publish what reading the attribute as a property would. On a `Post` resource, `$this->getAttribute('title')` and `$this->resource->getAttributeValue('title')` publish `string`, as `$this->title` does, and `$this->resource->getAttribute('author')` publishes the relation's type, `User`. That works on a relation's model and a closure parameter too, so `$this->whenLoaded('author', fn ($author) => $author->getAttribute('name'))` publishes `string` as an optional property. A name the model doesn't declare publishes `unknown`, and so does a relation read through `getAttributeValue()`, which returns no relation.
|
|
3166
|
+
|
|
2983
3167
|
`getKey()` publishes the key type on any model the package can name, including one a variable holds, such as a `whenLoaded()` closure parameter, a `map()` element, or a helper's `Post $post` parameter. So `$this->comments->map(fn ($comment) => $comment->getKey())` publishes `number[]`.
|
|
2984
3168
|
|
|
2985
3169
|
A model that no database row backs yet has no key, so its `getKey()` adds `| null`. That covers a model you build with `new`, `replicate()`, `replicateQuietly()` or `newInstance()`, and one that a query, a relation or a factory builds without saving it:
|
|
@@ -3176,67 +3360,51 @@ private function summary(Request $request): array
|
|
|
3176
3360
|
|
|
3177
3361
|
If one `return` can't be typed, or the method yields, the property publishes `unknown`.
|
|
3178
3362
|
|
|
3179
|
-
When you use the method's result as a value,
|
|
3363
|
+
When you use the method's result as a value, its array publishes what the same expressions publish in `toArray()`. That includes models, API resources, and enums, and the file imports what they name. One value differs. A backed enum case you write out, such as `PostStatus::Draft`, publishes the value it sends, `0`, instead of the enum's alias. A list of such cases publishes a list of their values, such as `(0 | 1)[]`.
|
|
3180
3364
|
|
|
3181
|
-
Here a `Post` casts `status` to the int-backed `PostStatus` enum, whose cases are `Draft = 0` and `Published = 1
|
|
3365
|
+
Here a `Post` casts `status` to the int-backed `PostStatus` enum, whose cases are `Draft = 0` and `Published = 1`, and `author` is a `BelongsTo` relation whose foreign key isn't nullable. The resource uses `card()` as a value:
|
|
3182
3366
|
|
|
3183
3367
|
```php
|
|
3184
3368
|
public function toArray(Request $request): array
|
|
3185
3369
|
{
|
|
3186
3370
|
return [
|
|
3187
|
-
'
|
|
3188
|
-
...$this->statusLabel($this->status),
|
|
3371
|
+
'card' => $this->card(),
|
|
3189
3372
|
];
|
|
3190
3373
|
}
|
|
3191
3374
|
|
|
3192
|
-
private function
|
|
3375
|
+
private function card(): array
|
|
3193
3376
|
{
|
|
3194
|
-
return [
|
|
3377
|
+
return [
|
|
3378
|
+
'author' => $this->author,
|
|
3379
|
+
'status' => $this->status,
|
|
3380
|
+
'status_resource' => EnumResource::make($this->status),
|
|
3381
|
+
'first_status' => PostStatus::Draft,
|
|
3382
|
+
];
|
|
3195
3383
|
}
|
|
3196
3384
|
```
|
|
3197
3385
|
|
|
3198
|
-
|
|
3386
|
+
Each member keeps its type, and `first_status` publishes the case's value:
|
|
3199
3387
|
|
|
3200
3388
|
```typescript
|
|
3201
|
-
import
|
|
3202
|
-
|
|
3203
|
-
export interface PostLabelResource {
|
|
3204
|
-
label: { name: "Draft" | "Published"; value: 0 | 1 };
|
|
3205
|
-
name: PostStatusKind;
|
|
3206
|
-
value: PostStatusType;
|
|
3207
|
-
}
|
|
3208
|
-
```
|
|
3209
|
-
|
|
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.
|
|
3211
|
-
|
|
3212
|
-
An `only()` or `except()` call names no class, so its result keeps its shape:
|
|
3213
|
-
|
|
3214
|
-
- A literal key list publishes its inline shape, with any enum- or model-typed member left `unknown`.
|
|
3215
|
-
- A runtime key list publishes `Record<string, unknown>`.
|
|
3216
|
-
- A to-many relation publishes `unknown[]`.
|
|
3217
|
-
|
|
3218
|
-
The same applies when the method reads an accessor whose getter calls `only()` or `except()`. A model that overrides `only()` or `except()` with a declared return type publishes that type instead. A model return, such as `: static`, becomes an object with the model's columns and appended accessors, narrowed to the literal keys. An enum or other class return leaves the value `unknown`.
|
|
3389
|
+
import { type AsEnum } from "@tolki/ts";
|
|
3219
3390
|
|
|
3220
|
-
|
|
3391
|
+
import { PostStatus } from "../../enums";
|
|
3392
|
+
import type { PostStatusType } from "../../enums";
|
|
3393
|
+
import type { User } from "../../models";
|
|
3221
3394
|
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
'author_role' => $this->user?->only(['id', 'role']),
|
|
3230
|
-
'replies' => $this->replies->only([1, 2]),
|
|
3231
|
-
];
|
|
3395
|
+
export interface PostCardResource {
|
|
3396
|
+
card: {
|
|
3397
|
+
author: User;
|
|
3398
|
+
status: PostStatusType;
|
|
3399
|
+
status_resource: AsEnum<typeof PostStatus>;
|
|
3400
|
+
first_status: 0;
|
|
3401
|
+
};
|
|
3232
3402
|
}
|
|
3233
3403
|
```
|
|
3234
3404
|
|
|
3235
|
-
|
|
3405
|
+
Written in `toArray()` itself, or spread with `...$this->card()`, `first_status` publishes `PostStatusType`.
|
|
3236
3406
|
|
|
3237
|
-
|
|
3238
|
-
summary: { id: number; author: { id: number; name: string }; author_role: { id: number; role: unknown } | null; replies: unknown[] };
|
|
3239
|
-
```
|
|
3407
|
+
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.
|
|
3240
3408
|
|
|
3241
3409
|
##### Resource Macros
|
|
3242
3410
|
|
|
@@ -3253,7 +3421,7 @@ JsonResource::macro('label', function (): string {
|
|
|
3253
3421
|
'model_label' => $this->resource->label(), // model_label: number
|
|
3254
3422
|
```
|
|
3255
3423
|
|
|
3256
|
-
`$this->resource->label()` calls the model directly, so it keeps the model's type. `$this?->label()`, `static::label()`, `self::label()` and `$this::label()` reach the macro, as `$this->label()` does. A method the resource declares or inherits, such as `whenLoaded()`, runs before any macro with its name, so a macro
|
|
3424
|
+
`$this->resource->label()` calls the model directly, so it keeps the model's type. `$this?->label()`, `static::label()`, `self::label()` and `$this::label()` reach the macro, as `$this->label()` does. A method the resource declares or inherits, such as `whenLoaded()`, runs before any macro with its name, so a macro doesn't change it. In a parent resource's body, `self::label()` looks only at that parent: if the parent doesn't declare `label()`, the macro runs even when the child declares one, and the key publishes the macro's type.
|
|
3257
3425
|
|
|
3258
3426
|
The package types a macro from its native return type, then its `@return` docblock, then its body. It reads the body without the values the call passes, so a body whose result depends on its arguments publishes `unknown`. It doesn't read the body of a closure declared outside a class method, such as in `bootstrap/app.php`. To type such a macro, give the closure a return type. A `@return` docblock works only on a closure declared inside a class, such as in a service provider's `boot()` method.
|
|
3259
3427
|
|
|
@@ -3364,7 +3532,34 @@ Some variables still publish `unknown`:
|
|
|
3364
3532
|
|
|
3365
3533
|
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
3534
|
|
|
3367
|
-
`preg_match()`
|
|
3535
|
+
`preg_match()` and `preg_match_all()` type their `$matches` from the pattern's groups and the flags you pass. After `preg_match('/(\w+)-(\d+)/', $this->slug, $matches)`, both `$matches` and `$matches ?? []` publish `string[]`. Named groups and flags change the shape:
|
|
3536
|
+
|
|
3537
|
+
```php
|
|
3538
|
+
preg_match('/(?<first>B)/', $this->title, $named);
|
|
3539
|
+
preg_match('/(B)/', $this->title, $offset, PREG_OFFSET_CAPTURE);
|
|
3540
|
+
preg_match('/(B)(x)?/', $this->title, $nulls, PREG_UNMATCHED_AS_NULL);
|
|
3541
|
+
preg_match_all('/(B)/', $this->title, $all);
|
|
3542
|
+
|
|
3543
|
+
return [
|
|
3544
|
+
'named' => $named,
|
|
3545
|
+
'first' => $named['first'] ?? null,
|
|
3546
|
+
'offset' => $offset ?? [],
|
|
3547
|
+
'nulls' => $nulls ?? [],
|
|
3548
|
+
'all' => $all,
|
|
3549
|
+
];
|
|
3550
|
+
```
|
|
3551
|
+
|
|
3552
|
+
Each key publishes the shape its call writes:
|
|
3553
|
+
|
|
3554
|
+
```typescript
|
|
3555
|
+
named: { "0": string; first?: string; "1"?: string } | never[];
|
|
3556
|
+
first: string | null;
|
|
3557
|
+
offset: [string, number][];
|
|
3558
|
+
nulls: (string | null)[];
|
|
3559
|
+
all: string[][];
|
|
3560
|
+
```
|
|
3561
|
+
|
|
3562
|
+
A named group's matches publish an object keyed by name and number, or `never[]` for the empty array a failed match leaves. A pattern the package can't read as a literal, such as one held in a variable, leaves `$matches ?? []` as `never[]`. A call that may not run, such as one inside an `if`, types `$matches` only when nothing else writes the variable.
|
|
3368
3563
|
|
|
3369
3564
|
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`.
|
|
3370
3565
|
|
|
@@ -3461,10 +3656,27 @@ if ($owner instanceof Post) {
|
|
|
3461
3656
|
return $data; // post_title?: string; user_email?: string
|
|
3462
3657
|
```
|
|
3463
3658
|
|
|
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
|
|
3659
|
+
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 can read a local variable, a closure parameter, a `foreach` value variable, or a chain of property reads on `$this`, such as `$this->imageable`.
|
|
3465
3660
|
|
|
3466
3661
|
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.
|
|
3467
3662
|
|
|
3663
|
+
A test on a `$this` property chain narrows reads of that same chain, so you don't need a local first. Here `imageable` is a `morphTo`:
|
|
3664
|
+
|
|
3665
|
+
```php
|
|
3666
|
+
if (! $this->imageable instanceof Post) {
|
|
3667
|
+
return ['title' => null];
|
|
3668
|
+
}
|
|
3669
|
+
|
|
3670
|
+
return ['title' => $this->imageable->title]; // title: string | null
|
|
3671
|
+
```
|
|
3672
|
+
|
|
3673
|
+
Each spelling narrows on its own, so a test on `$this->resource->imageable` doesn't narrow a read of `$this->imageable`. Because code between the test and a read could change the property, the narrowing ends at a write to the chain, at any write through a local, and at most calls, such as `$this->reload()`, `PostResource::make($this->resource)`, or a call on a local. These calls keep it:
|
|
3674
|
+
|
|
3675
|
+
- The resource's own helpers, such as `when()` and `whenLoaded()`
|
|
3676
|
+
- Gate and policy checks
|
|
3677
|
+
- Laravel's `route()` and `url()`
|
|
3678
|
+
- A call that's passed no local, no `$this`, and no `$this->resource`, such as `Str::limit($this->imageable->title, 50)`
|
|
3679
|
+
|
|
3468
3680
|
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.
|
|
3469
3681
|
|
|
3470
3682
|
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`.
|
|
@@ -3497,7 +3709,6 @@ return [
|
|
|
3497
3709
|
These forms don't narrow:
|
|
3498
3710
|
|
|
3499
3711
|
- **The ternary's own value**: `'either' => $either` publishes the whole union. Only reads through the variable narrow.
|
|
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.
|
|
3501
3712
|
- **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.
|
|
3502
3713
|
- **Mixed conditions in a ternary**: a test joined with `&&`, or an `||` chain that mixes negated and plain tests.
|
|
3503
3714
|
- **The arm the test doesn't prove**: `$this->resource instanceof SubscribedTeam ? null : $this->resource->subscriber` publishes `unknown`, since `Team` has no `subscriber` relation.
|
|
@@ -3525,7 +3736,7 @@ $picked = $this->id > 0 ? json_decode('"x"') : null; // string | null
|
|
|
3525
3736
|
|
|
3526
3737
|
The annotation follows these rules:
|
|
3527
3738
|
|
|
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 */`.
|
|
3739
|
+
- **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 */`. A `@phpstan-var` or `@psalm-var` tag wins over a plain `@var`, as in PHPStan.
|
|
3529
3740
|
- **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`.
|
|
3530
3741
|
- **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).
|
|
3531
3742
|
|
|
@@ -3538,14 +3749,18 @@ A write the package can't type keeps a model parameter's model, so after `$autho
|
|
|
3538
3749
|
The annotation's type counts only when it's built from these forms, and when every part of it resolves:
|
|
3539
3750
|
|
|
3540
3751
|
- Scalars: `int`, `string`, `bool`, `float`, `null`, `true`, and `false`
|
|
3541
|
-
- A class, interface, or enum that the file imports or
|
|
3542
|
-
- `
|
|
3752
|
+
- A class, interface, or enum that the file imports, writes in full, or declares in its own namespace
|
|
3753
|
+
- `self`, `static`, and `parent`, which name the classes `self::`, `static::`, and `parent::` reach in that method, as in an [inherited `toArray()`](#inheriting-a-parent-toarray). The variable may hold a subclass, so a read of a method or property a subclass can override takes its declared type, and publishes `unknown` where it has none. A closure parameter typed `self` or `parent` reads the same way.
|
|
3754
|
+
- `X[]`, `list<X>`, `array<int, X>`, `array<string, X>`, `array<int|string, X>`, `array<array-key, X>`, and `array<'a'|'b', X>`
|
|
3543
3755
|
- `array{...}` and `object{...}` shapes with plain or quoted keys, and `list{...}` tuples
|
|
3544
|
-
- `Collection<K, X>`, for both Laravel's support collection and its Eloquent collection
|
|
3756
|
+
- `Collection<X>` and `Collection<K, X>`, for both Laravel's support collection and its Eloquent collection
|
|
3757
|
+
- A type alias the class declares with `@phpstan-type`, or imports with `@phpstan-import-type`, under its own name or an `as` name
|
|
3545
3758
|
- A `callable` as a shape's member, which publishes `unknown`
|
|
3546
3759
|
- Unions of these forms, such as `Comment|User|null` or `list<User>|User`, and `?` before any form
|
|
3547
3760
|
|
|
3548
|
-
Any other type is ignored
|
|
3761
|
+
Any other type is ignored. A key that can be an `int` or a `string`, as in `array<int|string, Comment>` or `array<array-key, Comment>`, publishes both shapes PHP can send, `Comment[] | Record<string, Comment>`. A model or an enum inside a shape keeps its type, so `array{author: User, status: Status}` publishes `{ author: User; status: StatusType }`. A `?` before a shape adds `| null` even when a member already holds `null`, so `?array{a: ?int}` publishes `{ a: number | null } | null`.
|
|
3762
|
+
|
|
3763
|
+
A helper's or a closure's `@param` tag reads the same forms where the value passed in can't be typed. With `@param Collection<int, Comment> $comments`, a read such as `$comments->first()?->content` publishes `string | null`, and with `@param Pair $pair`, where `Pair` is a `@phpstan-type` alias, `$pair` takes the alias's shape. Where the value passed in is typed, its type wins over the tag.
|
|
3549
3764
|
|
|
3550
3765
|
#### Collection Pipelines
|
|
3551
3766
|
|
|
@@ -3579,7 +3794,9 @@ These helpers and methods publish as follows:
|
|
|
3579
3794
|
- **`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.
|
|
3580
3795
|
- **`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[]`.
|
|
3581
3796
|
- **`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`.
|
|
3582
|
-
- **`
|
|
3797
|
+
- **`keys()`**: publishes the list of the keys, `number[]` for a list and `string[]` for a `Record<string, X>`. A literal array lists its own keys, so `collect(['a' => 1, 200 => 'x'])->keys()->all()` publishes `('a' | 200)[]`.
|
|
3798
|
+
- **`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 scalar type hint holds the value PHP converts the element to, so `collect(['5'])->map(fn (int $v) => $v)->all()` publishes `number[]`. A write that replaces the parameter is followed into the body.
|
|
3799
|
+
- **`map()` callbacks**: besides a closure, the callback can be a first-class callable, such as `$this->shout(...)`, or a callable string, such as `'strtoupper'`. A `map()` over a `Record<string, X>` keeps its string keys, so it publishes a `Record` of what the callback returns.
|
|
3583
3800
|
|
|
3584
3801
|
Here `PromoCode` is a value object with a `string` property `code`:
|
|
3585
3802
|
|
|
@@ -3623,6 +3840,79 @@ A chain can start at `$this->resource` too. `$this->resource->comments->map(fn (
|
|
|
3623
3840
|
|
|
3624
3841
|
`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.
|
|
3625
3842
|
|
|
3843
|
+
##### Array Functions
|
|
3844
|
+
|
|
3845
|
+
PHP's array functions keep the element type too. `array_map()` with one array keeps that array's keys, so a list maps to a list and a string-keyed array to an object. With two or more arrays it publishes a list, and a `null` callback zips the arrays into tuples. The callback can be any callable, as with `map()`:
|
|
3846
|
+
|
|
3847
|
+
```php
|
|
3848
|
+
public function toArray(Request $request): array
|
|
3849
|
+
{
|
|
3850
|
+
return [
|
|
3851
|
+
'messages' => array_map(fn (array $row): string => $row['message'], $this->rows()),
|
|
3852
|
+
'doubled' => array_map(fn (int $count): int => $count * 2, ['low' => 1, 'high' => 2]),
|
|
3853
|
+
'zipped' => array_map(null, $this->labels(), $this->counts()),
|
|
3854
|
+
'names' => array_map('strtoupper', $this->comments->pluck('content')->all()),
|
|
3855
|
+
];
|
|
3856
|
+
}
|
|
3857
|
+
```
|
|
3858
|
+
|
|
3859
|
+
Here `rows()` returns `list<array{message: string}>`, `labels()` a `list<string>`, and `counts()` a `list<int>`:
|
|
3860
|
+
|
|
3861
|
+
```typescript
|
|
3862
|
+
export interface ArrayMapResource {
|
|
3863
|
+
messages: string[];
|
|
3864
|
+
doubled: { low: number; high: number };
|
|
3865
|
+
zipped: [string | null, number | null][];
|
|
3866
|
+
names: string[];
|
|
3867
|
+
}
|
|
3868
|
+
```
|
|
3869
|
+
|
|
3870
|
+
`array_keys()` publishes the list of the keys, as `keys()` does, so `array_keys(['a' => 1, 'b' => 2])` publishes `('a' | 'b')[]`.
|
|
3871
|
+
|
|
3872
|
+
`array_filter()` of an array shape makes each key optional and leaves out a key that only ever holds `null`. `array_values()` of the result publishes the list of the values left:
|
|
3873
|
+
|
|
3874
|
+
```php
|
|
3875
|
+
'shape' => array_filter(['a' => $this->title, 'b' => $this->published_at]),
|
|
3876
|
+
'no_null' => array_filter(['a' => $this->title, 'b' => null]),
|
|
3877
|
+
'values' => array_values(array_filter(['a' => $this->title, 'b' => $this->published_at])),
|
|
3878
|
+
```
|
|
3879
|
+
|
|
3880
|
+
Here `published_at` is a nullable column:
|
|
3881
|
+
|
|
3882
|
+
```typescript
|
|
3883
|
+
shape: { a?: string; b?: string };
|
|
3884
|
+
no_null: { a?: string };
|
|
3885
|
+
values: string[];
|
|
3886
|
+
```
|
|
3887
|
+
|
|
3888
|
+
A filter that keeps no key sends `[]`, not `{}`. Reading a key on it still gives `undefined`, as the optional keys allow, but code that checks for an array, such as `Array.isArray()`, sees one.
|
|
3889
|
+
|
|
3890
|
+
PHP throws a `TypeError` when you pass a collection to `array_map()`, `array_keys()`, `array_values()`, or `array_filter()`, so `ts:publish` warns and names the line. Call `->values()->all()` on the collection first.
|
|
3891
|
+
|
|
3892
|
+
#### Query Chains
|
|
3893
|
+
|
|
3894
|
+
A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be):
|
|
3895
|
+
|
|
3896
|
+
```php
|
|
3897
|
+
return [
|
|
3898
|
+
'author' => User::find(1),
|
|
3899
|
+
'author_name' => User::find(1)?->name,
|
|
3900
|
+
'latest' => Post::query()->first(),
|
|
3901
|
+
'first_id' => Post::query()->pluck('id')->first(),
|
|
3902
|
+
'admins' => User::query()->where('id', 1)->get(),
|
|
3903
|
+
];
|
|
3904
|
+
```
|
|
3905
|
+
|
|
3906
|
+
Each chain publishes what its last step returns:
|
|
3907
|
+
|
|
3908
|
+
```typescript
|
|
3909
|
+
author: User | null;
|
|
3910
|
+
author_name: string | null;
|
|
3911
|
+
latest: Post | null;
|
|
3912
|
+
first_id: number | null;
|
|
3913
|
+
admins: User[];
|
|
3914
|
+
```
|
|
3915
|
+
|
|
3626
3916
|
### Spreads and Inheritance
|
|
3627
3917
|
|
|
3628
3918
|
A resource can build its array from its parent class, its traits, and its own helper methods. Each one adds its properties to the interface.
|
|
@@ -3699,7 +3989,7 @@ The nearest class up the parent chain that declares a `toArray()` provides the s
|
|
|
3699
3989
|
The package reads the inherited body as PHP runs it for the child:
|
|
3700
3990
|
|
|
3701
3991
|
- `$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.
|
|
3992
|
+
- `self::` reaches the class that declares the body, and `parent::` reaches that class's parent. Spreads follow the same rule: `...parent::extra()` adds the keys of the parent's `extra()`, as `...self::extra()` and `...static::extra()` add those of the method each reaches. A private or abstract parent method adds none because PHP throws on that call, and neither does one whose body the package can't read in full.
|
|
3703
3993
|
- A `private` member stays the one in the class that declares `toArray()`, because PHP never overrides one.
|
|
3704
3994
|
|
|
3705
3995
|
```php
|
|
@@ -3912,7 +4202,7 @@ A variable that starts from `parent::toArray($request)` works the same way. See
|
|
|
3912
4202
|
|
|
3913
4203
|
#### Trait Method Spread
|
|
3914
4204
|
|
|
3915
|
-
Spread a trait method's return into `toArray()` with `...$this->method()`. Its body publishes the same types it would in `toArray()`, and its `@return array{...}` docblock types
|
|
4205
|
+
Spread a trait method's return into `toArray()` with `...$this->method()`. Its body publishes the same types it would in `toArray()`, and its `@return array{...}` docblock types what the body can't:
|
|
3916
4206
|
|
|
3917
4207
|
```php
|
|
3918
4208
|
trait IncludesMorphValue
|
|
@@ -3951,7 +4241,7 @@ export interface PostResource {
|
|
|
3951
4241
|
}
|
|
3952
4242
|
```
|
|
3953
4243
|
|
|
3954
|
-
Multi-line `@return` shapes work too:
|
|
4244
|
+
Multi-line `@return` shapes work too, as long as the type starts on the tag's own line, as PHPStan requires:
|
|
3955
4245
|
|
|
3956
4246
|
```php
|
|
3957
4247
|
/**
|
|
@@ -3991,6 +4281,27 @@ trait IncludesExtras
|
|
|
3991
4281
|
|
|
3992
4282
|
A key the body can't type, and that neither the `@return` docblock nor `#[TsCasts]` covers, publishes `unknown`.
|
|
3993
4283
|
|
|
4284
|
+
Keys follow PHP's order, so a later write replaces an earlier one with the same name, whether a key or a spread writes it. Here the resource wraps a value object whose `title` is a `string`, and the second spread replaces the `author` that `credited()` returns:
|
|
4285
|
+
|
|
4286
|
+
```php
|
|
4287
|
+
public function toArray(Request $request): array
|
|
4288
|
+
{
|
|
4289
|
+
return [
|
|
4290
|
+
'byline' => [
|
|
4291
|
+
...$this->credited(),
|
|
4292
|
+
...['author' => $this->resource->title],
|
|
4293
|
+
],
|
|
4294
|
+
];
|
|
4295
|
+
}
|
|
4296
|
+
|
|
4297
|
+
private function credited(): array
|
|
4298
|
+
{
|
|
4299
|
+
return ['id' => 1, 'author' => $this->resource->author];
|
|
4300
|
+
}
|
|
4301
|
+
```
|
|
4302
|
+
|
|
4303
|
+
The property publishes `byline: { id: number; author: string }`. When a spread always writes a key but the package can't type its value, the key publishes `unknown`, not the type it replaced. A spread of a local that sets the key only inside an `if` may leave the earlier value in place, so the key publishes both types. A merge is the exception, because Laravel never lets a merged key replace a key written before the merge, or a key written after the merge replace the merged one. See [Merge Operations](#merge-operations).
|
|
4304
|
+
|
|
3994
4305
|
Trait spreads carry through inheritance. When a parent resource spreads a trait method and a child spreads `...parent::toArray($request)`, the child gets the keys the trait contributed.
|
|
3995
4306
|
|
|
3996
4307
|
#### Bare Method-Call Return
|
|
@@ -4257,7 +4568,7 @@ trait GathersPermissions
|
|
|
4257
4568
|
/** Untyped, so only the docblocks above can type what it returns. */
|
|
4258
4569
|
protected function opaque()
|
|
4259
4570
|
{
|
|
4260
|
-
return $this->resource->
|
|
4571
|
+
return json_decode($this->resource->payload);
|
|
4261
4572
|
}
|
|
4262
4573
|
}
|
|
4263
4574
|
```
|
|
@@ -4276,14 +4587,101 @@ export interface PostPermissionsResource {
|
|
|
4276
4587
|
|
|
4277
4588
|
Both forms of `@return` count:
|
|
4278
4589
|
|
|
4279
|
-
- **An `array{...}` shape**: each key gets its own type, and a key written `key?:` also becomes optional. A string or number literal type, such as `'draft'|'live'` or `1|2|3`, publishes as written.
|
|
4280
|
-
- **`array<string, V>`**: `V`
|
|
4590
|
+
- **An `array{...}` shape**: each key gets its own type, and a key written `key?:` also becomes optional. A string or number literal type, such as `'draft'|'live'` or `1|2|3`, publishes as written. It also narrows a body type that admits every literal it lists, so `label: 'early'|'late'` over a `string` column publishes `label: 'early' | 'late'`.
|
|
4591
|
+
- **`array<string, V>`**: `V` is the entry for every key, and types each one as a shape's entry would.
|
|
4281
4592
|
|
|
4282
4593
|
`toArray()`'s own `@return array{...}` fills keys the same way.
|
|
4283
4594
|
|
|
4284
|
-
|
|
4595
|
+
Apart from the literal narrowing above, the body wins wherever it's specific, so a stale `@return` can't overwrite a type the package already knows. The docblock types what the body can't, at any depth:
|
|
4596
|
+
|
|
4597
|
+
- a key the body left vague, such as `unknown`, `unknown[]`, or `Record<string, unknown>`
|
|
4598
|
+
- a member or a list element the body couldn't type, inside a key it did type
|
|
4599
|
+
- a value the body [left out of a union](#values-left-out-of-a-union), beside the values it typed
|
|
4600
|
+
- an [interpolated key's](#interpolated-keys) value that the body left `unknown | undefined`
|
|
4601
|
+
|
|
4602
|
+
It keeps any `| null` the body found, and it doesn't add what the body proves Laravel never sends. An entry that only adds `| null` to the body's type, as `label` does below, publishes the body's type. A shape inside a key keeps the keys the body writes: a docblock key the body never writes is left out, unless the docblock marks it `key?:` or the array may hold keys the package can't name, such as a spread of an array with no element type.
|
|
4285
4603
|
|
|
4286
|
-
|
|
4604
|
+
This resource wraps a `ContactSheet` value object, as [Resources That Wrap Other Classes](#resources-that-wrap-other-classes) describes. Its `contacts` property lists `MailRecipient` objects, whose `name` is a `?string`. Its `extras` property is an `array` with no element type, `hint` has no type, and `title` is a `?string`:
|
|
4605
|
+
|
|
4606
|
+
```php
|
|
4607
|
+
/**
|
|
4608
|
+
* @property-read ContactSheet $resource
|
|
4609
|
+
*/
|
|
4610
|
+
class ContactSheetResource extends JsonResource
|
|
4611
|
+
{
|
|
4612
|
+
/**
|
|
4613
|
+
* @return array{
|
|
4614
|
+
* rows: list<array{name: string|null, locale: string}>,
|
|
4615
|
+
* summary: array{label: string|null, count: int|null}
|
|
4616
|
+
* }
|
|
4617
|
+
*/
|
|
4618
|
+
public function toArray(Request $request): array
|
|
4619
|
+
{
|
|
4620
|
+
$sheet = $this->resource;
|
|
4621
|
+
|
|
4622
|
+
return [
|
|
4623
|
+
'rows' => array_map(
|
|
4624
|
+
fn (MailRecipient $r) => [
|
|
4625
|
+
...$sheet->extras,
|
|
4626
|
+
'name' => $r->name,
|
|
4627
|
+
],
|
|
4628
|
+
$sheet->contacts,
|
|
4629
|
+
),
|
|
4630
|
+
'summary' => [
|
|
4631
|
+
'label' => (string) $sheet->title,
|
|
4632
|
+
'count' => $sheet->title !== null
|
|
4633
|
+
? $sheet->hint
|
|
4634
|
+
: null,
|
|
4635
|
+
],
|
|
4636
|
+
];
|
|
4637
|
+
}
|
|
4638
|
+
}
|
|
4639
|
+
```
|
|
4640
|
+
|
|
4641
|
+
Each row takes `locale` from the docblock, because the spread may hold it. `label` keeps the body's `string`, since `(string)` never sends `null`, and `count` takes the docblock's `number` in place of `$sheet->hint`:
|
|
4642
|
+
|
|
4643
|
+
```typescript
|
|
4644
|
+
export interface ContactSheetResource {
|
|
4645
|
+
rows: { name: string | null; locale: string }[];
|
|
4646
|
+
summary: { label: string; count: number | null };
|
|
4647
|
+
}
|
|
4648
|
+
```
|
|
4649
|
+
|
|
4650
|
+
Where a key's value has a different shape on each path, each shape stays its own member of the union, and the docblock adds keys only to a shape that may hold them. Under the same entry as `rows`, a row that one path builds as `['name' => $r->name]`, and another builds with `...$sheet->extras`, publishes `({ name: string | null } | { name: string | null; locale: string })[]`.
|
|
4651
|
+
|
|
4652
|
+
A shape value that names a model, an enum, or an API resource keeps it at any depth, and the file imports it. Here `tags` is a nullable column cast to `'array'`, which publishes `unknown[] | null` on its own, and `json_decode()` returns a value the package can't type:
|
|
4653
|
+
|
|
4654
|
+
```php
|
|
4655
|
+
/**
|
|
4656
|
+
* @return array{
|
|
4657
|
+
* tags: list<string>,
|
|
4658
|
+
* extra: array{author: User, status: PostStatus},
|
|
4659
|
+
* }
|
|
4660
|
+
*/
|
|
4661
|
+
public function toArray(Request $request): array
|
|
4662
|
+
{
|
|
4663
|
+
return [
|
|
4664
|
+
'tags' => $this->tags,
|
|
4665
|
+
'extra' => json_decode($this->extra_json, true),
|
|
4666
|
+
];
|
|
4667
|
+
}
|
|
4668
|
+
```
|
|
4669
|
+
|
|
4670
|
+
The docblock fills both keys, and `tags` keeps its `| null`:
|
|
4671
|
+
|
|
4672
|
+
```typescript
|
|
4673
|
+
import type { PostStatusType } from "../../enums";
|
|
4674
|
+
import type { User } from "../../models";
|
|
4675
|
+
|
|
4676
|
+
export interface PostExtrasResource {
|
|
4677
|
+
tags: string[] | null;
|
|
4678
|
+
extra: { author: User; status: PostStatusType };
|
|
4679
|
+
}
|
|
4680
|
+
```
|
|
4681
|
+
|
|
4682
|
+
A key that a spread method's `@return` fills because the body left it vague keeps its classes only when you spread the method at the top level of `toArray()`. Spread inside a nested array, as in `'meta' => [...$this->extras()]`, each model, enum, or API resource such a fill names publishes `unknown`. Type such a key with `#[TsCasts]` and an `import`. A key the body typed keeps its classes wherever you spread the method.
|
|
4683
|
+
|
|
4684
|
+
A name that isn't a PHP class, such as a type you declare only in TypeScript, publishes as written in a spread method's `@return`. In `toArray()`'s own `@return`, the key stays `unknown`, so type it with `#[TsCasts]`.
|
|
4287
4685
|
|
|
4288
4686
|
In a spread method, the branches count only while every `return` is an array literal, `[]`, or a variable the method builds. Otherwise, only the spread method's first `return` counts.
|
|
4289
4687
|
|
|
@@ -4802,11 +5200,13 @@ Here `pager` publishes `LengthAwarePaginator<UserResource> | null`.
|
|
|
4802
5200
|
|
|
4803
5201
|
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>`.
|
|
4804
5202
|
|
|
4805
|
-
|
|
5203
|
+
A read on the item `first()` or `last()` returns takes the type of the singular resource's model. In a `PostCollection` that collects `PostResource`, `$this->resource->first()?->title`, `$this->collection->first()?->title`, and `$this->collection->last()?->title` each publish `string | null`.
|
|
5204
|
+
|
|
5205
|
+
The package doesn't follow a collection pipeline on `$this->resource`, such as `map()`, `pluck()` or `values()`. Each publishes `unknown`. Type such a key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
4806
5206
|
|
|
4807
5207
|
#### Paginated Collections
|
|
4808
5208
|
|
|
4809
|
-
A collection's interface covers what its `toArray()` returns. The `links` and `meta` keys Laravel adds to a paginated response, and any data you add with `with()` or `additional()`, aren't part of it. An Inertia page prop that passes a paginator to a resource collection gets its pagination members from the page prop's type instead, with the `meta` block of each paginator kind. See [Paginating Inline in the Render Call](https://tolki.abe.dev/ts/inertia.html#paginating-inline-in-the-render-call) on the Inertia page.
|
|
5209
|
+
A collection's interface covers what its `toArray()` returns. The `links` and `meta` keys Laravel adds to a paginated response, and any data you add with `with()` or `additional()`, aren't part of it. An Inertia page prop that passes a paginator to a resource collection gets its pagination members from the page prop's type instead, with the `meta` block of each paginator kind. An Inertia prop's type also carries the `with()` and `additional()` keys. See [Paginating Inline in the Render Call](https://tolki.abe.dev/ts/inertia.html#paginating-inline-in-the-render-call) on the Inertia page.
|
|
4810
5210
|
|
|
4811
5211
|
Over a paginator, Laravel merges a `meta` or `links` key that your `toArray()` returns beside `data` into its own pagination block with `array_merge_recursive()`, and it merges the `with()` and `additional()` data the same way. A key your `toArray()` adds, such as `links.self`, is in the page prop's type. A key that two of these name, such as `meta.total`, is sent as a list of both values, such as `[3, 3]`, while the type still says `number`. Give your key another name, or remove from `paginationInformation()` only the key your `toArray()` also sends. The package doesn't read `paginationInformation()`, so any other change there leaves the published pagination type wrong.
|
|
4812
5212
|
|
|
@@ -4982,7 +5382,8 @@ The package already types these shapes without an override:
|
|
|
4982
5382
|
- A method call on an enum, a date, a model, or a service, and a property read on any of those or on a value object. See [Method Return Types](#method-return-types).
|
|
4983
5383
|
- A value behind a local variable, a closure-local variable, or an `instanceof` guard. See [Local Variables and Narrowing](#local-variables-and-narrowing).
|
|
4984
5384
|
- 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).
|
|
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).
|
|
5385
|
+
- A key that only some branches return, or one that `toArray()`'s or a spread method's `@return` describes. See [Return Branches and `@return` Shapes](#return-branches-and-return-shapes).
|
|
5386
|
+
- A model, an enum, or an API resource in the array of a method you use as a value. See [Methods Declared as a Bare `array`](#methods-declared-as-a-bare-array).
|
|
4986
5387
|
|
|
4987
5388
|
`#[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.
|
|
4988
5389
|
|
|
@@ -5485,7 +5886,7 @@ final class PostScheduled implements ShouldBroadcast
|
|
|
5485
5886
|
|
|
5486
5887
|
private function publishedAt() // no return type
|
|
5487
5888
|
{
|
|
5488
|
-
return $this->post->
|
|
5889
|
+
return json_decode($this->post->schedule)->published_at;
|
|
5489
5890
|
}
|
|
5490
5891
|
}
|
|
5491
5892
|
```
|
|
@@ -5499,7 +5900,7 @@ export interface PostScheduled {
|
|
|
5499
5900
|
}
|
|
5500
5901
|
```
|
|
5501
5902
|
|
|
5502
|
-
The body still wins wherever it types a value. The docblock only
|
|
5903
|
+
The body still wins wherever it types a value, so a stale `@return` can't overwrite a type the body already found. The docblock types only what the body can't, at any depth, such as a key the body left `unknown`, a member inside a key it typed, or a value it left out of a union. It follows the same rules as an [API resource's `@return`](https://tolki.abe.dev/ts/api-resources.html#return-branches-and-return-shapes). A `key?:` entry in the docblock makes that key optional.
|
|
5503
5904
|
|
|
5504
5905
|
A spread helper that builds its keys by interpolation, such as `"{$name}_tag"`, adds an index signature to the interface, for example ``[key: `${string}_tag`]: string | undefined``. When the helper's body can't type the values, its `@return array<string, V>` docblock types them. [Interpolated Keys](https://tolki.abe.dev/ts/api-resources.html#interpolated-keys) on the API Resources page describes how the event's `#[TsCasts]` and `extends` clause then apply.
|
|
5505
5906
|
|
|
@@ -5549,6 +5950,58 @@ export interface ManifestAssembled {
|
|
|
5549
5950
|
|
|
5550
5951
|
[Building the Array in a Variable](https://tolki.abe.dev/ts/api-resources.html#building-the-array-in-a-variable) on the API Resources page lists the writes the package follows.
|
|
5551
5952
|
|
|
5953
|
+
A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be). `Post::query()->pluck('id')->first()` publishes `number | null`. A model the chain returns is presented as `Partial<Model>`, as a [model property](#model--enum-aware-properties) is, so `User::find($this->userId)` publishes `Partial<User> | null` and `User::query()->where('id', 1)->get()` publishes `Partial<User>[]`.
|
|
5954
|
+
|
|
5955
|
+
An `EnumResource` around an enum that may be `null` adds `| never[]`, and so does each element of a `map()` of such wraps, because an event sends the empty resource as `[]`.
|
|
5956
|
+
|
|
5957
|
+
#### `when()` and `unless()` From `Conditionable`
|
|
5958
|
+
|
|
5959
|
+
An event that uses Laravel's `Conditionable` trait can call `$this->when()` and `$this->unless()` in `broadcastWith()`. Unlike a resource's `when()`, they always send the key: the callback's value when the condition holds, the default's when it doesn't, and the event itself where either one returns `null` or no default is passed. The key publishes that union, required:
|
|
5960
|
+
|
|
5961
|
+
```php
|
|
5962
|
+
class PostPinned implements ShouldBroadcast
|
|
5963
|
+
{
|
|
5964
|
+
use Conditionable;
|
|
5965
|
+
|
|
5966
|
+
public function __construct(public Post $post) {}
|
|
5967
|
+
|
|
5968
|
+
public function broadcastWith(): array
|
|
5969
|
+
{
|
|
5970
|
+
$pinned = $this->post->is_pinned;
|
|
5971
|
+
|
|
5972
|
+
return [
|
|
5973
|
+
'label' => $this->when($pinned, fn () => 'active'),
|
|
5974
|
+
'with_default' => $this->when(
|
|
5975
|
+
$pinned,
|
|
5976
|
+
fn () => 'pinned',
|
|
5977
|
+
fn () => 'unpinned',
|
|
5978
|
+
),
|
|
5979
|
+
];
|
|
5980
|
+
}
|
|
5981
|
+
|
|
5982
|
+
public function broadcastOn(): Channel
|
|
5983
|
+
{
|
|
5984
|
+
return new Channel('posts');
|
|
5985
|
+
}
|
|
5986
|
+
}
|
|
5987
|
+
```
|
|
5988
|
+
|
|
5989
|
+
`label` can send the event itself, whose JSON is its public `post` property:
|
|
5990
|
+
|
|
5991
|
+
```typescript
|
|
5992
|
+
import type { Post } from "../models";
|
|
5993
|
+
|
|
5994
|
+
/** @see App\Events\PostPinned */
|
|
5995
|
+
export interface PostPinned {
|
|
5996
|
+
label: string | { post: Post };
|
|
5997
|
+
with_default: string;
|
|
5998
|
+
}
|
|
5999
|
+
```
|
|
6000
|
+
|
|
6001
|
+
The event's own JSON joins the type only when the package knows it. An event `make:event` generates uses `InteractsWithSockets`, whose untyped `$socket` property leaves that JSON unknown, so a key that can send such an event publishes `unknown`. Pass a default that returns a value, as `with_default` does, or type the key with [`#[TsCasts]`](#overriding-property-types-with-tscasts).
|
|
6002
|
+
|
|
6003
|
+
A resource built around the call, such as `UserResource::make($this->when(…))`, is always sent too, so it publishes required.
|
|
6004
|
+
|
|
5552
6005
|
### Model & Enum-Aware Properties
|
|
5553
6006
|
|
|
5554
6007
|
A property typed as an Eloquent model or a PHP enum resolves to the type the rest of the package uses for it. The file imports that type for you:
|
|
@@ -5964,11 +6417,11 @@ class UserResource extends JsonResource
|
|
|
5964
6417
|
}
|
|
5965
6418
|
```
|
|
5966
6419
|
|
|
5967
|
-
Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page.
|
|
6420
|
+
Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page. A bare value sends no object: `'status' => Status::Published->value` publishes that case's own value, `1`. [Reading `->value` and `->name`](https://tolki.abe.dev/ts/enums.html#reading-value-and-name) covers bare values and `cases()`.
|
|
5968
6421
|
|
|
5969
|
-
The same rewrite applies to [Inertia shared data](https://tolki.abe.dev/ts/inertia.html). With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations.
|
|
6422
|
+
The same rewrite applies to [Inertia shared data](https://tolki.abe.dev/ts/inertia.html). With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations. Route page props are rewritten the same way. See the `EnumResource` notes in [How the Augmentation File Is Generated](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
|
|
5970
6423
|
|
|
5971
|
-
`EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object.
|
|
6424
|
+
`EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object. As an Inertia page prop or shared value, Inertia sends `[]` instead, so the prop publishes `AsEnum<typeof Status> | never[]`. A broadcast event's payload, and a `map()` of wraps kept as a collection inside another resource, send `[]` too, and publish `| never[]`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource).
|
|
5972
6425
|
|
|
5973
6426
|
### Response Shape
|
|
5974
6427
|
|
|
@@ -6277,6 +6730,8 @@ export const ExcludableEnum = defineEnum({
|
|
|
6277
6730
|
|
|
6278
6731
|
export type ExcludableEnumType = "alpha" | "beta";
|
|
6279
6732
|
export type ExcludableEnumKind = "Alpha" | "Beta";
|
|
6733
|
+
|
|
6734
|
+
export type ExcludableEnum = ExcludableEnumType;
|
|
6280
6735
|
```
|
|
6281
6736
|
|
|
6282
6737
|
`overridden()` and `overriddenStatic()` have attributes that would include them whatever the auto-include settings, but `#[TsExclude]` removes them. `label()` and `secret()` are missing because auto-include is off. Turn on `enums.auto_include_methods`, and `label()` publishes while `secret()` stays out. See [Auto-Including All Enum Methods](https://tolki.abe.dev/ts/enums.html#auto-including-all-enum-methods) for which methods auto-include adds.
|
|
@@ -7225,17 +7680,19 @@ This page covers shared data, and the API resources that shared data and a route
|
|
|
7225
7680
|
With `inertia.enabled` on (the default), the package builds the file from your middleware:
|
|
7226
7681
|
|
|
7227
7682
|
- **Finding the middleware**: the package searches `inertia.inertia_middleware_path`, or `app_path()` when that isn't set, for a class that extends `Inertia\Middleware`. If it finds none, it writes no file. If your app has more than one such class, point `inertia.inertia_middleware_path` at the directory that holds the one you want.
|
|
7228
|
-
- **Reading `share()`**: every key's value is typed from your code, without handling a real request. A `share()` that a trait supplies is read too, and so is one that builds its array in a variable and returns it. A key that the variable gets on only some paths, such as inside an `if`, is optional.
|
|
7229
|
-
- **Parent middleware**: a `...parent::share($request)` spread and `array_merge(parent::share($request), [...])` are both read, all the way up your middleware's parent classes. A later key overrides an earlier one and keeps the earlier one's position, as PHP does.
|
|
7683
|
+
- **Reading `share()`**: every key's value is typed from your code, without handling a real request. A `share()` that a trait supplies is read too, even under an alias such as `use SharesProps { base as share; }`, and so is one that builds its array in a variable and returns it. A key that the variable gets on only some paths, such as inside an `if`, is optional.
|
|
7684
|
+
- **Parent middleware**: a `...parent::share($request)` spread and `array_merge(parent::share($request), [...])` are both read, all the way up your middleware's parent classes. A later key overrides an earlier one and keeps the earlier one's position, as PHP does. A parent's `#[TsCasts]` applies too, as [Type Resolution Priority](#type-resolution-priority) describes.
|
|
7685
|
+
- **Dotted keys**: Inertia unpacks a top-level dotted key into nested objects, so `'auth.name' => $request->user()?->name` publishes `auth: { name: string | null }`. When the array also holds an `auth` array, `name` is added to it.
|
|
7230
7686
|
- **Integer keys**: Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. Nested keys keep theirs.
|
|
7231
|
-
-
|
|
7687
|
+
- **The signed-in user**: `$request->user()` is typed through your live auth config, from `auth.defaults.guard` to that guard's provider to the provider's `model`. The prop becomes `User | null`, and the file imports the model's type for you. `auth()->user()`, `Auth::user()`, `request()->user()` and `Auth::guard()->user()` resolve the same way, and so does a read past any of them, such as `auth()->user()?->name`, which publishes `string | null`. `auth()->id()` and `Auth::id()` publish the user's key, as described below.
|
|
7232
7688
|
- **Request helpers**: `$request->url()`, `fullUrl()`, `path()`, `integer()`, `boolean()`, `string()`, `cookie()` and `hasCookie()` are typed from Laravel's own signatures.
|
|
7233
7689
|
- **`config()`**: `config('some.key')` with a literal key is typed from the live config value, since the package runs inside your booted app. A computed key stays `unknown`.
|
|
7234
7690
|
- **Value helpers**: `now()` and `today()` are typed as `string`, or `Date` under [`timestamps_as_date`](https://tolki.abe.dev/ts/models.html#timestamps-as-date-objects). `str($value)` is typed as `string`, and `str()` with no argument as `Record<string, never>`. `url($path)` is typed as `string` when the path can't be `null`, and stays `unknown` when it can or has no type. `collect([...])` and a bare array literal are both typed as the list or object the array encodes as, such as `string[]` for `['a', 'b']`. `+` on two arrays is typed as PHP's array union, where the left side's keys win.
|
|
7235
|
-
- **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns.
|
|
7236
|
-
- **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap
|
|
7691
|
+
- **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns. That includes one inside an array that a helper method builds.
|
|
7692
|
+
- **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap, and so does a prop class you construct, such as `new OptionalProp(fn () => …)`. The three a partial reload can leave out, `defer`, `optional` and `lazy`, make the key optional.
|
|
7237
7693
|
- **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.
|
|
7238
7694
|
- **`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`.
|
|
7695
|
+
- **`EnumResource` ternaries and `null`**: each arm of a ternary is typed as Laravel sends it. Wrapping two different enums publishes `AsEnum<typeof Role> | AsEnum<typeof Status>`, and a wrap beside a bare case of the same enum publishes `AsEnum<typeof Status> | StatusType`. A wrap around an enum that may be `null` publishes `AsEnum<typeof Status> | never[]`, because Inertia sends `[]` for it, not `null`. Tell the two apart with `Array.isArray()`.
|
|
7239
7696
|
- **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
7697
|
- **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).
|
|
7241
7698
|
- **`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.
|
|
@@ -7245,9 +7702,11 @@ With `inertia.enabled` on (the default), the package builds the file from your m
|
|
|
7245
7702
|
|
|
7246
7703
|
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.
|
|
7247
7704
|
|
|
7705
|
+
The signed-in user is typed from the default guard only, so a named guard, such as `auth('admin')->user()` or `Auth::guard('admin')->user()`, publishes `unknown`. When your guards' providers name more than one user model, a route's guard middleware can sign in either one, so `request()->user()`, `Auth::guard()->user()` and a read past `auth()->user()`, `Auth::user()` or `request()->user()` publish `unknown` too. `$request->user()`, a bare `auth()->user()` or `Auth::user()`, `auth()->id()` and `Auth::id()` keep the default guard's model. Type such a key with [`#[TsCasts]`](#type-resolution-priority).
|
|
7706
|
+
|
|
7248
7707
|
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[]`.
|
|
7249
7708
|
|
|
7250
|
-
A
|
|
7709
|
+
A few mixes of `EnumResource` arms publish a type that doesn't match what Laravel sends. A wrap beside a bare case of another enum, as in `$cond ? EnumResource::make(Role::Admin) : Status::Draft`, publishes `RoleType | StatusType`, though the first arm sends the `Role` object. A nested ternary over the wraps of three enums can leave a type alias unimported, which fails your build with `TS2304`. Override such a key with a `#[TsCasts]` entry that has an `import`.
|
|
7251
7710
|
|
|
7252
7711
|
### Anatomy of the Generated File
|
|
7253
7712
|
|
|
@@ -7304,13 +7763,13 @@ export {};
|
|
|
7304
7763
|
|
|
7305
7764
|
Each part of the file does one job:
|
|
7306
7765
|
|
|
7307
|
-
- **`import type { User } from "./app/models";`**: every model, resource or enum that a prop type names gets an import at the top, with a path relative to the output root. An `EnumResource` prop is the exception under the default `enums.use_tolki_package`. It renders as `AsEnum<typeof Role>`, so the enum's const is imported as a value (`import { Role } from './app/enums';`), under an `import { type AsEnum } from '@tolki/ts';` line, and both come before the `import type` lines. Imports from an `import` key in `#[TsCasts]` join the `import type` lines.
|
|
7766
|
+
- **`import type { User } from "./app/models";`**: every model, resource or enum that a prop type names gets an import at the top, with a path relative to the output root. An `EnumResource` prop is the exception under the default `enums.use_tolki_package`. It renders as `AsEnum<typeof Role>`, so the enum's const is imported as a value (`import { Role } from './app/enums';`), under an `import { type AsEnum } from '@tolki/ts';` line, and both come before the `import type` lines. Imports from an `import` key in `#[TsCasts]` join the `import type` lines. Two classes that share a name, such as `App\Enums\Status` and `App\Crm\Enums\Status`, are imported under aliases, as in `StatusType as CrmStatusType`.
|
|
7308
7767
|
- **`declare global { namespace Inertia { type SharedData = ...; } }`**: makes `Inertia.SharedData` available by name in any `.ts` file in your project. That includes the generated route files, which combine it with each page's props, as [Inertia Integration](https://tolki.abe.dev/ts/routing.html#inertia-integration) shows.
|
|
7309
7768
|
- **`declare module '@inertiajs/core' { ... }`**: augments Inertia's own `InertiaConfig`, so `usePage().props` is typed across your frontend without you writing the augmentation.
|
|
7310
7769
|
- **`errorValueType: string[]`**: added only when the middleware sets `protected $withAllErrors = true;`. It matches the shape Inertia uses for its validation errors in that mode.
|
|
7311
7770
|
- **`export {};`**: TypeScript accepts a `declare global` block only in a module, a file with at least one top-level `import` or `export`. This line makes the file a module even when it has no imports.
|
|
7312
7771
|
|
|
7313
|
-
The file imports only the names its types use. A key you override with `#[TsCasts]` drops the
|
|
7772
|
+
The file imports only the names its types use. A key you override with `#[TsCasts]` drops the imports its inferred type needed, but keeps the import of a class the override names and the key's value holds. `'owner' => 'User | null'` over `$request->user()` still imports `User`, with no `import` key.
|
|
7314
7773
|
|
|
7315
7774
|
A key that isn't a plain identifier, such as `'can-edit'` or `42`, is quoted, as in `"can-edit": boolean`. Route files quote a page prop's key the same way.
|
|
7316
7775
|
|
|
@@ -7320,8 +7779,8 @@ A value the package can't read stays `unknown`. `'flash' => ['success' => fn ()
|
|
|
7320
7779
|
|
|
7321
7780
|
Each key from `share()` takes its type from the first of these that covers it:
|
|
7322
7781
|
|
|
7323
|
-
1. **`#[TsCasts]`** on the middleware class or on its `share()` method. When both name a key, the method's entry wins, even when the two spell an index signature's name differently. It's the same attribute [models](https://tolki.abe.dev/ts/models.html#tscasts), [API resources](https://tolki.abe.dev/ts/api-resources.html#overriding-property-types-with-tscasts) and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html#overriding-property-types-with-tscasts) use.
|
|
7324
|
-
2. **A `@return array{...}` docblock** on `share()`. You write the shape by hand, for a key the package can't infer, such as a method call whose return type says nothing. A `key?:` entry makes that key optional.
|
|
7782
|
+
1. **`#[TsCasts]`** on the middleware class or on its `share()` method. When both name a key, the method's entry wins, even when the two spell an index signature's name differently. A parent middleware's entries apply too when your middleware inherits the parent's `share()` or reads it through `parent::share()`, and your class's entries win over the parent's. It's the same attribute [models](https://tolki.abe.dev/ts/models.html#tscasts), [API resources](https://tolki.abe.dev/ts/api-resources.html#overriding-property-types-with-tscasts) and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html#overriding-property-types-with-tscasts) use.
|
|
7783
|
+
2. **A `@return array{...}` docblock** on `share()`. You write the shape by hand, for a key the package can't infer, such as a method call whose return type says nothing. A `key?:` entry makes that key optional. A model or enum that a top-level key names, as in `owner: User`, is imported for you.
|
|
7325
7784
|
3. **Inference from your code**, the default. It covers plain values, nested arrays, conditionals, closures, spreads, `array_merge()`, `config()`, the request and auth helpers, and Inertia's prop wrappers.
|
|
7326
7785
|
|
|
7327
7786
|
A key that `#[TsCasts]` or the docblock names but `share()` doesn't return is added to the type.
|
|
@@ -7354,7 +7813,7 @@ Here `appName` takes its type from `#[TsCasts]` and `flash` takes its type from
|
|
|
7354
7813
|
|
|
7355
7814
|
### API Resources in Props
|
|
7356
7815
|
|
|
7357
|
-
Inertia sends an API resource prop as the resource's whole response, the same JSON a route that returns the resource sends. That holds at any depth of a route's page props and in `share()`,
|
|
7816
|
+
Inertia sends an API resource prop as the resource's whole response, the same JSON a route that returns the resource sends. That holds at any depth of a route's page props and in `share()`, including props that a helper method or another class's method builds, as in `Inertia::render('Posts/Show', $this->props->build())`. Each prop publishes that response:
|
|
7358
7817
|
|
|
7359
7818
|
```php
|
|
7360
7819
|
return Inertia::render('Posts/Show', [
|
|
@@ -7380,10 +7839,34 @@ Each kind of prop follows its own rule:
|
|
|
7380
7839
|
- **`Resource::collection()`** publishes `AnonymousResourceCollection<CommentResource>` from `@tolki/types`, which is `{ data: CommentResource[] }`.
|
|
7381
7840
|
- **A named collection** publishes its own interface, which already holds its wrap key. One whose `toArray()` returns no wrap key publishes `{ data: TagCollection }`, because Laravel nests that body under `data`.
|
|
7382
7841
|
- **`->toResourceCollection()`** with no argument publishes the collection Laravel guesses. Over an empty collection, Laravel skips the guess and sends `{ data: [] }`, so the prop also publishes that empty response, such as `UserCollection | { data: never[] }` or, over `paginate()`, `| JsonResourcePaginator<never>`. A guessed collection whose response is only its `data` list already fits it and gets no extra type.
|
|
7842
|
+
- **Keys beside `data`**: the keys that a resource's `with()` method or an `->additional([...])` call adds are published beside the body. A single resource merges them into its object, as in `{ data: PostResource; meta: { total: number } }`, and any other response is intersected with them, as in `AnonymousResourceCollection<CommentResource> & { meta: { total: number } }`. A `with()` key that a `when()` call may leave out arrives as `[]`, so it publishes `T | never[]`.
|
|
7843
|
+
- **A resolved resource**, from `->resolve()`, publishes the resource's own type, with no `data` key. Inertia still sends each API resource inside the resolved body as a response, so a key that holds one publishes that response, as the example below shows. `Resource::collection(...)->resolve()` publishes a list of the same.
|
|
7383
7844
|
|
|
7384
|
-
|
|
7845
|
+
Here `PostCardResource` returns `'author' => UserCardResource::make($this->author)` among its keys:
|
|
7385
7846
|
|
|
7386
|
-
|
|
7847
|
+
```php
|
|
7848
|
+
return Inertia::render('Posts/Show', [
|
|
7849
|
+
'post' => PostResource::make($post)->additional([
|
|
7850
|
+
'meta' => ['total' => $post->comments()->count()],
|
|
7851
|
+
]),
|
|
7852
|
+
'card' => PostCardResource::make($post)->resolve(),
|
|
7853
|
+
]);
|
|
7854
|
+
```
|
|
7855
|
+
|
|
7856
|
+
Both props publish what Inertia sends:
|
|
7857
|
+
|
|
7858
|
+
```typescript
|
|
7859
|
+
export type ShowPageProps = Inertia.SharedData & {
|
|
7860
|
+
post: { data: PostResource; meta: { total: number } };
|
|
7861
|
+
card: Omit<PostCardResource, "author"> & {
|
|
7862
|
+
author: { data: UserCardResource };
|
|
7863
|
+
};
|
|
7864
|
+
};
|
|
7865
|
+
```
|
|
7866
|
+
|
|
7867
|
+
After `->resolve()`, a resource collection class with its own `toArray()` publishes its items bare, though Inertia sends each one under `data`. Pass the collection itself, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
|
|
7868
|
+
|
|
7869
|
+
The wrap key is the one your app sets by the time `ts:publish` runs, as [The Wrap Key Your App Sets](https://tolki.abe.dev/ts/api-resources.html#the-wrap-key-your-app-sets) describes. After `JsonResource::withoutWrapping()`, a single resource publishes the bare `PostResource`, and `Resource::collection()` over items that aren't paginated publishes `CommentResource[]`. Over a paginator, Laravel keeps the `data` key. Keys from `with()` or `additional()` also make Laravel nest the resource under `data`, and the prop publishes it that way. After `JsonResource::wrap('items')`, a single resource publishes `{ items: PostResource }`.
|
|
7387
7870
|
|
|
7388
7871
|
#### JSON:API Resources in Props
|
|
7389
7872
|
|
|
@@ -7458,7 +7941,7 @@ export type IndexPageProps = Inertia.SharedData & {
|
|
|
7458
7941
|
};
|
|
7459
7942
|
```
|
|
7460
7943
|
|
|
7461
|
-
`paginate()`, `simplePaginate()`, and `cursorPaginate()` are all recognized, in the `new SomeCollection(...)`, `SomeResource::collection(...)`, and `->toResourceCollection()` forms.
|
|
7944
|
+
`paginate()`, `simplePaginate()`, and `cursorPaginate()` are all recognized, in the `new SomeCollection(...)`, `SomeResource::collection(...)`, and `->toResourceCollection()` forms. The paginator can also come from a query builder held in a variable, or from a controller method or an injected service's method, typed from the method's return type or its body. A call that hands back the same paginator, such as `withQueryString()`, `appends()` or `onEachSide()`, keeps its kind.
|
|
7462
7945
|
|
|
7463
7946
|
Each paginator sends its own `meta` block, so each gets its own type from `@tolki/types`. A named collection adds the pagination type to its own interface. An anonymous collection, from `SomeResource::collection(...)`, publishes the paginator's whole response, and so does a collection with `$wrap = null`, because Laravel sends it under `data` over a paginator. In this list, the named form comes first, and `R` is the collected resource:
|
|
7464
7947
|
|
|
@@ -7468,17 +7951,16 @@ Each paginator sends its own `meta` block, so each gets its own type from `@tolk
|
|
|
7468
7951
|
|
|
7469
7952
|
A prop that can hold more than one paginator kind, such as a ternary over `paginate()` and `simplePaginate()`, publishes `TeamCollection & (ResourceSimplePagination | ResourcePagination)`. One that can hold a plain collection or a paginator publishes both shapes, `TeamCollection | (TeamCollection & ResourcePagination)`. A collection that `share()` returns is typed the same way.
|
|
7470
7953
|
|
|
7471
|
-
When the package
|
|
7954
|
+
When the package can't tell which paginator a payload holds, the prop gets the collection's type without the pagination part, a wrong type rather than a missing one. That happens with a method declared to return the `Paginator` contract, which more than one paginator kind implements, or with one that has no return type and a body the package can't read:
|
|
7472
7955
|
|
|
7473
7956
|
```php
|
|
7474
|
-
|
|
7475
|
-
|
|
7957
|
+
// page() is declared to return the Paginator contract
|
|
7476
7958
|
return Inertia::render('Posts/Index', [
|
|
7477
|
-
'posts' => new PostCollection($
|
|
7959
|
+
'posts' => new PostCollection($this->posts->page()),
|
|
7478
7960
|
]);
|
|
7479
7961
|
```
|
|
7480
7962
|
|
|
7481
|
-
Here `posts` types as `PostCollection`, without `& ResourcePagination
|
|
7963
|
+
Here `posts` types as `PostCollection`, without `& ResourcePagination`. A paginator passed without a resource is typed only from a query chain that starts at a model, or from a method that returns one. From a query builder held in a variable, it publishes `unknown`. Declare the paginator class the method returns, such as `LengthAwarePaginator`, build the paginator in the props, or type the prop with [`#[TsCasts]`](https://tolki.abe.dev/ts/routing.html#overriding-props-with-tscasts).
|
|
7482
7964
|
|
|
7483
7965
|
### Output Location
|
|
7484
7966
|
|
|
@@ -8189,11 +8671,12 @@ The package reads the props argument as an expression, not only as an array lite
|
|
|
8189
8671
|
public function show(Post $post, Request $request): Response
|
|
8190
8672
|
{
|
|
8191
8673
|
return Inertia::render('Posts/Show', [
|
|
8192
|
-
'post' => $post,
|
|
8674
|
+
'post' => $post->load('author:id,name'),
|
|
8193
8675
|
'comments' => Comment::query()->latest()->get(),
|
|
8194
8676
|
'author' => $request->user(),
|
|
8677
|
+
'viewer' => auth()->user()?->name,
|
|
8195
8678
|
'page' => $request->integer('page'),
|
|
8196
|
-
'related' => Post::query()->paginate(10),
|
|
8679
|
+
'related' => Post::query()->paginate(10)->withQueryString(),
|
|
8197
8680
|
'tally' => Inertia::defer(fn () => Comment::query()->count()),
|
|
8198
8681
|
]);
|
|
8199
8682
|
}
|
|
@@ -8203,32 +8686,54 @@ This generates:
|
|
|
8203
8686
|
|
|
8204
8687
|
```typescript
|
|
8205
8688
|
export type ShowPageProps = Inertia.SharedData & {
|
|
8206
|
-
post: Post;
|
|
8689
|
+
post: Post & { author: Pick<User, "id" | "name"> };
|
|
8207
8690
|
comments: Comment[];
|
|
8208
8691
|
author: User | null;
|
|
8692
|
+
viewer: string | null;
|
|
8209
8693
|
page: number;
|
|
8210
8694
|
related: LengthAwarePaginator<Post>;
|
|
8211
8695
|
tally?: number;
|
|
8212
8696
|
};
|
|
8213
8697
|
```
|
|
8214
8698
|
|
|
8215
|
-
|
|
8699
|
+
Eloquent finders and collections are typed step by step from the model the chain starts at:
|
|
8700
|
+
|
|
8701
|
+
| Call | Type |
|
|
8702
|
+
| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
|
8703
|
+
| `find()`, `first()`, `firstWhere()` | `Model \| null` |
|
|
8704
|
+
| `findOrFail()`, `firstOrFail()`, `sole()`, `create()`, `make()`, `firstOrCreate()`, `firstOrNew()`, `updateOrCreate()` | `Model` |
|
|
8705
|
+
| `all()`, `get()`, `cursor()`, `findMany()`, and `find()` with a list of keys | `Model[]` |
|
|
8706
|
+
| `pluck('title')` | A list of the column's type |
|
|
8707
|
+
| `value('title')` | The column's type, or `null` |
|
|
8708
|
+
| `count()` | `number` |
|
|
8709
|
+
| `exists()` | `boolean` |
|
|
8216
8710
|
|
|
8217
|
-
|
|
8711
|
+
A relation step moves the chain to the related model, so `Post::find(1)->comments()->get()` is `Comment[]`. A read past a finder is typed too, so `Post::find(1)?->title` is `string | null`.
|
|
8712
|
+
|
|
8713
|
+
These expressions are typed too:
|
|
8714
|
+
|
|
8715
|
+
- **Paginators**: `paginate()`, `simplePaginate()` and `cursorPaginate()` are `LengthAwarePaginator<Model>`, `SimplePaginator<Model>` and `CursorPaginator<Model>`, imported from `@tolki/types`. A call that hands back the same paginator, such as `withQueryString()` or `appends()`, keeps that type, and `through()` types the items as its callback returns them.
|
|
8218
8716
|
- **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[]`.
|
|
8219
|
-
-
|
|
8220
|
-
-
|
|
8717
|
+
- **`load()` and `loadMissing()`**: the model with the relations the call loads, such as `Post & { author: User }`, or a list of that on a collection. A column list publishes a `Pick`, as the example shows, and a dotted path nests, so `load('author.posts')` is `Post & { author: User & { posts: Post[] } }`. A to-one relation adds `| null` where a closure may filter it out, or where a column list leaves out the key Laravel matches it by. Only the value the call returns carries the relations, so call `load()` inside the prop: `$post->load('author');` on its own line, followed by `'post' => $post`, publishes `Post`.
|
|
8718
|
+
- **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`. Two enums with the same class name in different namespaces are imported under aliases, such as `StatusType as CrmStatusType`. An `EnumResource` prop publishes `AsEnum<typeof Status>`, as it does in [shared data](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
|
|
8719
|
+
- **The signed-in user**: `$request->user()`, `auth()->user()`, `Auth::user()` and `request()->user()`, and reads past them such as `auth()->user()?->name`, typed through your `auth` config the same way [shared data](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated) is. A named guard, or guards that name more than one user model, can leave some of these `unknown`, as that page describes. `Request` reads such as `integer()`, `boolean()`, `string()` and `url()` are typed too.
|
|
8221
8720
|
- **`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.
|
|
8222
|
-
- **Inertia v2 prop wrappers**: `defer()`, `optional()` and `lazy()` type as the value they wrap and make the key optional, since a partial reload can leave it out. `always()`, `merge()` and `deepMerge()` type as the value they wrap.
|
|
8223
|
-
- **API resources and resource collections**, typed as the response Inertia sends for each, such as `{ data: PostResource }` for a single resource and `JsonResourceSimplePaginator<PostResource>` over `simplePaginate()`, including a `#[PreserveKeys]` collection's keyed `data` member. See [API Resources in Props](https://tolki.abe.dev/ts/inertia.html#api-resources-in-props).
|
|
8224
|
-
- **A props array assigned from a ternary
|
|
8225
|
-
- **
|
|
8721
|
+
- **Inertia v2 prop wrappers**: `defer()`, `optional()` and `lazy()` type as the value they wrap and make the key optional, since a partial reload can leave it out. `always()`, `merge()` and `deepMerge()` type as the value they wrap. A prop class you construct, such as `new OptionalProp(fn () => …)`, types the same as its factory.
|
|
8722
|
+
- **API resources and resource collections**, typed as the response Inertia sends for each, such as `{ data: PostResource }` for a single resource and `JsonResourceSimplePaginator<PostResource>` over `simplePaginate()`, including a `#[PreserveKeys]` collection's keyed `data` member, the keys `with()` and `additional()` add, and the resources nested in a resource you call `->resolve()` on. See [API Resources in Props](https://tolki.abe.dev/ts/inertia.html#api-resources-in-props).
|
|
8723
|
+
- **A props array in a local variable**, typed from what your code writes to it before the render call. The local can be assigned from a ternary, set one key at a time, assigned in each arm of an `if`, or built with `$base + [...]`. A key written after the render call isn't published, because the call has already copied the array, and keys a loop writes under an interpolated name publish an index signature.
|
|
8724
|
+
- **Props a helper builds**: props built whole by a controller helper method or by a method on an injected service, as in `Inertia::render('Posts/Show', $this->service->build())`, are typed the same way, closures and API resources included.
|
|
8725
|
+
- **Closures and first-class callables**: Inertia calls a callable prop, so `fn () => $this->label()` and `$this->label(...)` are both typed from what the call returns.
|
|
8726
|
+
|
|
8727
|
+
A prop the package can't read is typed `unknown`, and the run carries on. Use [`#[TsCasts]`](#overriding-props-with-tscasts) to set its type. A few shapes the package doesn't follow:
|
|
8728
|
+
|
|
8729
|
+
- A props local that a `+=` writes, or one written inside a `switch`, a `try`, or a loop that exits through `continue` or `break`, publishes none of its keys, so the page's type is only `Inertia.SharedData`. Build the props as an array literal instead.
|
|
8730
|
+
- A first-class callable that a constructor stores in a property, as in `$this->stamp = now(...)`, publishes `Record<string, never>`, and `ts:publish` warns, though Inertia calls it and sends what it returns. Set that prop's type with `#[TsCasts]`.
|
|
8226
8731
|
|
|
8227
|
-
|
|
8732
|
+
Inertia unpacks a top-level dotted key into nested objects, so `'filters.page' => $request->integer('page')` publishes `filters: { page: number }`. When the props also hold a `filters` array, `page` is added to it.
|
|
8228
8733
|
|
|
8229
|
-
A
|
|
8734
|
+
A page key with the same name as a shared-data key publishes both types intersected, though Inertia sends only the page's value. Give page keys names that shared data doesn't use.
|
|
8230
8735
|
|
|
8231
|
-
Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. Nested keys keep theirs.
|
|
8736
|
+
Inertia merges shared data and page props with `array_merge()`, which renumbers integer keys from `0`. A top-level `42 => …` key therefore publishes as `"0"`, and `ts:publish` warns that you probably meant a string key. A render call that can send one of several arrays, such as the arms of a ternary, numbers each array on its own. Nested keys keep theirs.
|
|
8232
8737
|
|
|
8233
8738
|
Sometimes the package can't analyze an action at all, for example because a class the action depends on fails to load. That route then publishes as a plain helper with no page-props type, and `ts:publish` names the action in a warning after the run. The rest of the run still finishes.
|
|
8234
8739
|
|
|
@@ -8266,11 +8771,14 @@ export type IndexPageProps = Inertia.SharedData & {
|
|
|
8266
8771
|
};
|
|
8267
8772
|
```
|
|
8268
8773
|
|
|
8774
|
+
An entry with no `import` key that names a class the prop's value holds, such as `'post' => 'Post | null'` over a route-bound `Post`, imports that class for you.
|
|
8775
|
+
|
|
8269
8776
|
### Inertia UI Table Props
|
|
8270
8777
|
|
|
8271
8778
|
A route that renders an [Inertia UI Table](https://inertiaui.com/) gets a typed page prop. The package reads the table's model from the table class itself, and never creates the table or calls its `toArray()`:
|
|
8272
8779
|
|
|
8273
8780
|
```php
|
|
8781
|
+
use App\Models\Post;
|
|
8274
8782
|
use App\Tables\PostTable;
|
|
8275
8783
|
use Inertia\Inertia;
|
|
8276
8784
|
|
|
@@ -8278,6 +8786,7 @@ public function index()
|
|
|
8278
8786
|
{
|
|
8279
8787
|
return Inertia::render('Posts/Index', [
|
|
8280
8788
|
'posts' => PostTable::make()->defaultSort('-id'),
|
|
8789
|
+
'total' => Post::query()->count(),
|
|
8281
8790
|
]);
|
|
8282
8791
|
}
|
|
8283
8792
|
```
|
|
@@ -8290,16 +8799,18 @@ import type { Post } from "../models";
|
|
|
8290
8799
|
|
|
8291
8800
|
export type IndexPageProps = Inertia.SharedData & {
|
|
8292
8801
|
posts: TableResource<Post>;
|
|
8802
|
+
total: number;
|
|
8293
8803
|
};
|
|
8294
8804
|
```
|
|
8295
8805
|
|
|
8806
|
+
A table is one prop like any other: the render call's other props keep their types, and the action's [`#[TsCasts]`](#overriding-props-with-tscasts) applies. `new PostTable`, a table held in a local variable, one in props a service method builds, and one in [shared data](https://tolki.abe.dev/ts/inertia.html) are typed the same way.
|
|
8807
|
+
|
|
8296
8808
|
`TableResource` is imported from whichever Inertia UI Table package your `package.json` lists, `@inertiaui/table-vue` or `@inertiaui/table-react`. If neither is listed, the import uses `@inertiaui/table-vue`. To force a package, or to use an alias, set `inertia.ui_table_package` in `config/ts-publish.php`.
|
|
8297
8809
|
|
|
8298
|
-
The package finds a table's model in
|
|
8810
|
+
The package finds a table's model in either of these places:
|
|
8299
8811
|
|
|
8300
8812
|
- A `$resource` property default, as in `protected ?string $resource = Post::class;`.
|
|
8301
8813
|
- A `query(): Builder` method that returns `Post::query()`, `Post::class`, or a query chain that starts at the model.
|
|
8302
|
-
- A service method: when the controller passes `$this->tables->index($request)`, the array that method returns can hold table props.
|
|
8303
8814
|
|
|
8304
8815
|
A table whose model exists only at runtime, for example one set in its constructor, gets no table type. Use [`#[TsCasts]`](#overriding-props-with-tscasts) on the controller method to type its props.
|
|
8305
8816
|
|
|
@@ -8350,6 +8861,19 @@ export const store = annotateRequestPayload<StorePostRequest>()(
|
|
|
8350
8861
|
);
|
|
8351
8862
|
```
|
|
8352
8863
|
|
|
8864
|
+
### Bundling
|
|
8865
|
+
|
|
8866
|
+
A route nobody uses drops out of your bundle: `defineRoute`, `getRouteDefaults` and the other runtime helpers are marked as free of side effects, except `setRouteDefaults`, `addRouteDefault` and `resetRouteDefaults`, which change shared state and are always kept. A plain `export const index = defineRoute({...})` drops in Vite (Rolldown), Rollup, webpack and Rspack. esbuild keeps it unless the call site is marked:
|
|
8867
|
+
|
|
8868
|
+
```typescript
|
|
8869
|
+
export const index = /* @__PURE__ */ defineRoute({
|
|
8870
|
+
url: "/users",
|
|
8871
|
+
methods: ["get"],
|
|
8872
|
+
});
|
|
8873
|
+
```
|
|
8874
|
+
|
|
8875
|
+
The curried shapes, `annotatePageProps<T>()(defineRoute({...}))` and `annotateRequestPayload<T>()(defineRoute({...}))`, drop in Rollup and Rspack as they are. Rolldown, esbuild and webpack need `/* @__PURE__ */` before each call: the outer one and the inner `defineRoute`. [Bundling and Tree-Shaking](https://tolki.abe.dev/tree-shaking.html) lists every bundler.
|
|
8876
|
+
|
|
8353
8877
|
### Filtering & Excluding Routes
|
|
8354
8878
|
|
|
8355
8879
|
These settings leave routes out of the published output:
|
|
@@ -8868,7 +9392,7 @@ To change what `ts:publish` itself does, replace one of its stages instead. See
|
|
|
8868
9392
|
|
|
8869
9393
|
`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.
|
|
8870
9394
|
|
|
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,
|
|
9395
|
+
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()` and `unless()`, which events and other classes can use, return the callback's result, the default's, or the object itself, so the key is always sent. `analyze()` types the key that way, required, as a publish does, and a resource built around the call, such as `UserResource::make($this->when(…))`, comes back required too. See [`when()` and `unless()` From `Conditionable`](https://tolki.abe.dev/ts/broadcast-events.html#when-and-unless-from-conditionable).
|
|
8872
9396
|
|
|
8873
9397
|
This example analyzes a service class's `toPayload()` method:
|
|
8874
9398
|
|
|
@@ -8995,7 +9519,7 @@ Outside those cases, `analyze()` runs the same inference that resources, broadca
|
|
|
8995
9519
|
|
|
8996
9520
|
`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.
|
|
8997
9521
|
|
|
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`.
|
|
9522
|
+
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`. Where the method's `@return` types the key that holds it, the docblock's type takes the left-out value's place beside the `null`, as [Values Left Out of a Union](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union) describes.
|
|
8999
9523
|
|
|
9000
9524
|
### Configuration Reference
|
|
9001
9525
|
|