Open ykrods opened 1 week ago
I don't know where in the tool chain the problem is, so sorry if this is not the proper place to report it. Thanks for your hard work on Svelte!
I believe the correct way to declare types for $state
is:
let p = $state<Person | undefined>(undefined);
This will fix it
Unsure why your way errors out though - The Typescript magic works in mysterious way
From a TypeScript perspective this works as expected, because TypeScript does not see that p
is assigned to anything else until it comes across p
inside the $derived
. Therefore moving the type definition onto the generic fixes this.
Essentially duplicate of:
(Appeal n to move that kit issue.)
Thanks for responses!
Based on the received advise, I have confirmed that the following code fixes the error.
let p1 = $state<Person>()
let p2 = $state<Person | undefined>()
let p3 = $state<Person | undefined>(undefined)
let p4: Person | undefined = $state()
let p5: Person | undefined = $state<Person | undefined>(undefined)
Please let me know if it is better to close this issue and discuss it further in another issue.
I understand now that if the type is not specified in generics, an error occurs due to a mismatch between the return type ( Person | undefined
) and the argument type ( undefined
) in the type inference (More precisely, the type of p is undefined
when type-checking is performed because of the syntax of $derived
, and the type of p becomes never
since it never reaches the end of the optional chain),
so how about define another generics variable for the argument?
As an example, changing the type of $state as follows could also fix the error.
declare function $state<T, U extends T = T>(initial: U): T;
( I am not used to typescript, so I can't judge if there is a problem with the code :skull: )
I think that maintainability, robustness, or other important features should take precedence over this, but I think it is simpler to write a state without explicit generics.
Describe the bug
On a project generated by
create-vite@5.5.5
, running a type check to the following code will get a result thatp
is typed asnever
.This is considered a bug because it does not occur when the following changes are made.
Reproduction
https://github.com/ykrods/svelte-reproduction-state-type
Logs
System Info
Severity
annoyance