#Client side typescript

7 messages · Page 1 of 1 (latest)

next krakenBOT
#

Hi @stoic lily. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, it is possible to use TypeScript without using an inline script in Astro. Astro ships with built-in support for TypeScript. You can import .ts and .tsx files directly in your Astro project, and even write TypeScript code directly inside your Astro component.

Here is an example of how you can import TypeScript in your Astro project:

import { getUser } from './user';
import type { UserType } from './user';

You can also write TypeScript code directly inside your Astro component script:

<script>
 // Processed! Bundled! TypeScript-supported!
 // Importing local scripts and Node modules works.
</script>

However, Astro doesn’t perform any type checking itself. Type checking should be taken care of outside of Astro, either by your IDE or through a separate script. For type checking Astro files, the astro check command is provided.

Please note that per TypeScript’s module resolution rules, .ts and .tsx file extensions should not be used when importing TypeScript files. Instead, either use .js/.jsx file extensions or completely omit the file extension.

import { getUser } from './user.js'; // user.ts
import MyComponent from "./MyComponent"; // MyComponent.tsx

For more information, you can refer to the Astro TypeScript Guide (https://docs.astro.build/en/guides/typescript/) and the Astro Imports Guide (https://docs.astro.build/en/guides/imports#typescript).

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@stoic lily kapa.ai is still learning and improving, please let us how it did by reacting below

stoic lily
#

@next kraken I meant using TypeScript in the client

next krakenBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, you can use TypeScript in client-side scripts in Astro. You can write your scripts as separate .ts files and reference them in a <script> tag’s src attribute. Astro will build, optimize, and add these scripts to the page for you.

Here is an example of how you can use TypeScript in client-side scripts:

<!-- also works for local TypeScript files -->
<script src="./script-with-types.ts"></script>

However, please note that Astro’s default bundling behavior will be disabled in some situations. In particular, adding type="module" or any attribute other than src to a <script> tag will cause Astro to treat the tag as if it had an is:inline directive. The same will be true when the script is written in a JSX expression.

For more information, you can refer to the Astro Client-side Scripts Guide (https://docs.astro.build/en/guides/client-side-scripts).

Source: Astro Client-side Scripts Guide (https://docs.astro.build/en/guides/client-side-scripts)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: