Repository navigation
$apps/paths + Typescript checking: am I going about this the wrong way? #17444
Replies: 7 comments 3 replies
|
This is unfortunately a limitation with TypeScript strings. Since You could create a helper such as this example. Note how the prop type is a narrower string literal and the helper function type casts the concatenation to a literal type |
|
You generally should not be using |
This comment was marked as spam.
This comment was marked as spam.
|
kit 3.0.1 has <script lang="ts">
import { assets } from '$app/manifest';
import { asset } from '$app/paths';
let { sessionFolder }: { sessionFolder: string } = $props();
// relative to static/, with a trailing slash
let thumbnail = $derived(
assets.find((entry) => entry.path === `${sessionFolder}thumbnail.jpg`)
);
</script>
{#if thumbnail}
<img src={asset(thumbnail.path)} alt="Session thumbnail" />
{:else}
<p>thumbnail unavailable</p>
{/if}
the fallback handles a missing file. this lookup only covers files present at build time keep |
|
Hi dustinfreeman! I think your concern makes sense. Having hundreds of valid assets but still getting TypeScript errors when building their paths dynamically can be frustrating. One alternative worth considering is Vite's Since you're working with session folders, you could move the images you want bundled into For example: const images = import.meta.glob(
'/src/lib/sessions/**/thumbnail.jpg',
{
eager: true,
query: '?url',
import: 'default'
}
) as Record<string, string>;You could then use the session folder name to look up the appropriate image URL from that map. This avoids passing a dynamically concatenated string into SvelteKit's strictly typed The important trade-off is that the files need to be known at build time, and this approach works with imported assets rather than files remaining in For your existing setup, the Vite documents glob imports here: Hope this gives you another option! If it resolves your question, feel free to mark the answer that helped as accepted. |
|
Two clean ways to handle this without disabling type checking:
|
|
For assets whose names are known at build time, keep the complete path literal: const thumbnailSrc = asset('sessions/demo/thumbnail.jpg');
const bannerSrc = asset('sessions/demo/banner.jpg');For a truly dynamic directory/session value, model the allowed values explicitly when possible: const thumbnails = {
demo: asset('sessions/demo/thumbnail.jpg'),
launch: asset('sessions/launch/thumbnail.jpg'),
} as const;
type Session = keyof typeof thumbnails;
export function thumbnailFor(session: Session): string {
return thumbnails[session];
}If the files are user-generated or otherwise cannot be enumerated at build time, they are not a good fit for const sessionNamePattern = /^[a-z0-9-]+$/;
export function sessionAssetUrl(session: string, file: 'thumbnail.jpg' | 'banner.jpg') {
if (!sessionNamePattern.test(session)) {
throw new Error('Invalid session name');
}
return `/sessions/${session}/${file}`;
}That avoids disabling checking globally and avoids an unchecked cast. If you have already validated that a value is a valid generated asset, a cast to |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
TL; DR it is impossible to call
asset(assetPath), where assetPath is of typestring, without throwing a typescript error, because the type checker is strict and checks if the specific asset exists.It feels like I'm using
asset()from$apps/pathsin a counterproductive way, and throwing a lot of irrelevant Typescript errors, even though all assets load correctly at runtime. Most likely, my intuition is wrong, but perhaps there's a quality of life improvement in SvelteKit here?I'm using:
I have assets in the
./static/directory of my SvelteKit project, grouped into folders. For the static adapter, I'm using default options:I have Svelte components that take a "session folder" as property, then load the relevant assets, like so:
This works fine:
const thumbnail_src = asset('<sub-path in static>/<session-name>/thumbnail.jpg');First attempt
However, the sessionFolder line shows Typescript error:
Argument of type '"<sub-path in static>/<session-name>/"' is not assignable to parameter of type <all ~500 assets in asset folder>This is probably fine and as-intended, since
asset()is meant to be a safety check for asset existence, and a directory doesn't count if you intend to do something with the asset.Second attempt
It seems like the way I should use asset() is:
const thumbnail_src = asset(sessionFolder + 'thumbnail.jpg');However, this throws a type error similar to the above:
Argument of type 'string' is not assignable to parameter of type <all ~500 assets in asset folder>`
The type-checking strictness of asset feels...unhelpful?
More Type Strictness
Notably, even this throws the
Argument of type 'string' is not assignable to parameter of type...error, since the post-concatenation type is string:What Should I do?
a. is it recommended to turn off type-checking for asset overall?
b. should asset strings always be passed around as full, constant strings?
c. should I be explicitly casting to ResolvedPathName ? This would feel cumbersome...
d. something else?
e. should SvelteKit be changed to accommodate my needs?
All reactions