typing CreateResource
I would like to do something like this so typescript don't show an error when using it in jsx:
const [data, { mutate }] = createResource<{ dataExample: string } | undefined>(() =>
getData("/api/Example")
);
So i can do:
<p>{data()?.dataExample}</p>
25 Replies
It should be inferred if you type (or cast) the result from getData
Not sure exactly about the type parameters of createResource itself
@foolswisdom but i want to reuse the getData function
You can just cast the result when you use it in the resource
this is the error with that cast:
Conversion of type 'Promise<undefined>' to type '{ dataExample: string; }' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Property 'dataExample' is missing in type 'Promise<undefined>' but required in type '{ dataExample: string; }'.ts(2352)
with the unknown first it looks like this, a bit too much i think
I found another way but it implies typing the res of the getData as any
Something like this(the function is not finished with the error handling it's just an example):
Oh it's just because getData is async
Should be able to cast to
yep it's a http request
yep i tried this
but don't work either
Huh
it works for me
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
Are you able to reproduce your types not working in the playground so they're easier to debug?
yep but you are returning the exact object you want i can't do that
it's a generic getData function
the object could be any shape
it works with the res typed as any
Right, so if it's generic can't you have a generic type param in the function:
idk too much about generics but this don't solve too
maybe you can use the playground you made and make a request to a public api with the correct way to use generics https://alexwohlbruck.github.io/cat-facts/docs/endpoints/facts.html
I'll try to do that tomorrow if you can't
is incorrect to type the res as any?
this is the only way to don't get errors of typescript at the moment
Sure, gimme a couple of mins
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
It's fine to be honest, imo just a little nicer to cast the result within the function itself
ohhh now i see
Thanks
i was typing
instead of but the first works too idk what i was doing wrong
instead of but the first works too idk what i was doing wrong
Haha things do sometimes just break randomly lol
generics it's like another way to type an any ? what's the diference?
the way you put i mean in the getData function
there's not much honestly
it just removes the explicit any cast
hmm i see
and it means you don't have to do the
getData("url") as any as <type>
every time you use it. It just becomes getData<<type>>()
but i was not typing any in the call of getData
only in the res var declaration inside the getData