Best practice for supporting static and reactive args

If I want to create a reactive function that takes in either a static or reactive arg like this:
function createRequest(resource: string | Accessor<string>) {
return createResource(
typeof resource === "function" ? resource : () => resource,
resource => fetch(resource)...
);
}
function createRequest(resource: string | Accessor<string>) {
return createResource(
typeof resource === "function" ? resource : () => resource,
resource => fetch(resource)...
);
}
I always wondered if there's a better alternative to string | Accessor<string> to support the following static and reactive scenarios:
function Reactive() {
const [dynamicResource, ...] = createSignal("/resourceA");
const data = createRequest(dynamicResource);
...
}

function Static() {
const data = createRequest("/resourceA");
...
}
function Reactive() {
const [dynamicResource, ...] = createSignal("/resourceA");
const data = createRequest(dynamicResource);
...
}

function Static() {
const data = createRequest("/resourceA");
...
}
2 Replies
chanon_s
chanon_s2mo ago
Yes, I wonder too if there is some kind of standard utiltiy for this
bigmistqke
bigmistqke2mo ago
I have AccessorMaybe<T> = Accessor<T> | T type util and const resolve = (fn: AccessorMaybe<T>): T => typeof fn === 'function' ? fn() : fn that I use a lot

Did you find this page helpful?