You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The following typings (a nullable state and a function signature with an optional param that derives another value) produce a type error Error: Property 'elements' does not exist on type 'never'.
Example code that produces the error:
export interface InspectResult {
elements: Array<Element>
point?: Point
selector?: string
}
function buildBoundingBoxes(elements?: Array<Element>): Array<BoundingBox> | null {
}
let inspectResult: InspectResult | null = $state(null)
let boundingBoxes: Array<BoundingBox> | null = $derived(buildBoundingBoxes(inspectResult?.elements))
The fix was to use $derived.by for code that should be valid with $derived. Either $derived or $derived.by work at runtime the same. The only problem was the type error during svelte-check.
Obviously, the concept of reactive expressions doesn't even exist in TS. So TS thinks that when buildBoundingBoxes(inspectResult?.elements)) is executed, inspectResult can only be null. And then it seems to face this issue microsoft/TypeScript#41766.
It seems another workaround is inspectResult!?.elements.
Yeah this is a type narrowing issue, and the type is widened in the lambda.
Another way to get around it is to type the $state generic: let foo = $state<boolean | null>(null)
Giving this the documentation label because there's not much we can do.
Why wouldn't derived.by be the API style of derived and drop derived.by? I'm not sure why compiler magic that necessitates a duplicate rune to work around trumps having a natural API.
Describe the bug
The following typings (a nullable state and a function signature with an optional param that derives another value) produce a type error
Error: Property 'elements' does not exist on type 'never'.
Example code that produces the error:
The fix was to use $derived.by for code that should be valid with $derived. Either $derived or $derived.by work at runtime the same. The only problem was the type error during svelte-check.
Reproduction
With the $derived type error
With the $derived.by fix
Logs
System Info
System: OS: macOS 14.4.1 CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz Memory: 318.56 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 20.9.0 - /usr/local/bin/node npm: 10.1.0 - /usr/local/bin/npm pnpm: 8.6.3 - /usr/local/bin/pnpm Browsers: Chrome: 123.0.6312.107 Safari: 17.4.1 npmPackages: svelte: 5.0.0-next.95 => 5.0.0-next.95
Severity
annoyance
The text was updated successfully, but these errors were encountered: