Skip to content

improve the typing of static assets import #16425

Description

@GoodBoyNinja

Describe the problem

I am trying to figure out whether there is an official way to get strong types from typescripts when importing an asset from the static folder, to avoid issues at runtime.

My current approach is:

import { asset } from "$app/paths";
type Asset = Parameters<typeof asset>[0];
type ExtractLiterals<T> = T extends any
  ? string extends T
    ? never
    : T
  : never;

const someAsset: ExtractLiterals<Asset> =
  "/asset.png";

The type Asset (which comes from the arguments of asset) does provide a template literal type which contains all the info about the files in the static folder, but it also is of type (string & {}) which makes it accept any string by default.

The helper ExtractLiterals in this case makes it strongly typed, is there a built in way to achieve this? I assume it would be very useful to have one if not.

Thank you!

Describe the proposed solution

I would like to see an official AssetId type export that is not a union of type (string & {}), same way there is RouteId type. This would help avoid errors in runtime.

For example:

import type { AssetId } from "$app/types";
const someAsset: AssetId = "/asset.png";

Alternatives considered

No response

Importance

nice to have

Additional Information

Using a typescript helper such as:

type ExtractLiterals<T> = T extends any
  ? string extends T
    ? never
    : T
  : never;

to remove the (string & {}) part of the original type

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions