DEV Community

Cover image for Getting Started with SvelteKit and TypeScript
Carlos Espinoza πŸ‡¨πŸ‡·
Carlos Espinoza πŸ‡¨πŸ‡·

Posted on

Getting Started with SvelteKit and TypeScript

Svelte JS is one of the most famous frameworks for web development and has become one of the most loved by the developer community due to its simple syntax, easy state management and more.

On the other hand TypeScript is the best choice for developing any project due to its static typing and its good performance in large scale projects.

SvelteKit + TypeScript

SvelteKit is a recently released framework that is powered by Svelte and includes great advantages such as a flexible and powerful routing system and others, It is a great alternative to develop medium and large scale projects, it integrates many tools to speed up the development.

In this tutorial you will learn how to integrate both tools in a project:

Note: Before you start make sure you have Node JS installed on your machine

First, let's generate a new SvelteKit project

npm create svelte@latest my-project-name
Enter fullscreen mode Exit fullscreen mode
  • Choose to use a skeleton project. And follow the next steps: first step Second step

Now go to your project folder:

cd my-project-name
Enter fullscreen mode Exit fullscreen mode
npm install
Enter fullscreen mode Exit fullscreen mode
//to actively check for TS errors in our code runs
npm run check:watch
Enter fullscreen mode Exit fullscreen mode

And that' s it 😎, we already have our SvelteKit project configured with TypeScript, now let's see how TypeScript looks like inside Svelte, for this we are going to fetch an API.

Go to index.svelte and make sure to add the TS support, as follows:

  <script lang="ts">

  </script> 
Enter fullscreen mode Exit fullscreen mode

In this occasion we will be fetching a test API, also we will be using axios which you can install running in your terminal npm install axios

The api we will be working with has the following format

  {
      "id": 1,
      "email": "George.@example.com",
      "first_name": "George",
      "last_name": "Bluth",
      "avatar": "https://reqres.in/img/faces/1-image.jpg"
  } 
Enter fullscreen mode Exit fullscreen mode

The first thing we will do is to define a TS interface and a function to fetch from the API

interface User {
   id: number;
   email: string;
   first_name: string;
   last_name: string;
   avatar: string;
}

type userData = {
    data: User[];
};

const getUser = async (url: string): Promise<User> => {
   // here we can use axios to get the user from the API
}
Enter fullscreen mode Exit fullscreen mode

Let's complete our function

const getUsersData = async (url: string): Promise<User> => {
    const { data, status } = await axios.get<userData>(url);
    if (status === 200) {
        console.log(JSON.stringify(data.data));
        return data.data;
    } else {
            throw new Error('Something went wrong');
    }
};

const userRespose = getUsersData("https://reqres.in/api/users");
Enter fullscreen mode Exit fullscreen mode

We will see something like this in the terminal, which means that our code is working correctly πŸ₯³ and we are getting the data:

data fetched

Now we just need to display this data in our HTML πŸ‘ŒLet's see how this would work in Svelte:

{#await usersRespose}
    <p>...loading</p>
    {:then result}
        {#each result as user}
            <div class="user">
                <p>{user.id} - {user.first_name} {user.last_name}</p>
                <img src={user.avatar} alt={user.name}>
            </div>
        {/each}
    {:catch error}
        <p>Upps! {error}</p>
{/await}
Enter fullscreen mode Exit fullscreen mode

Let's add a bit of CSS to style the result:

<style>
    .user {
        display: flex;
        align-items: center;
        margin: 20px;
    }
    .user img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-left: 10px;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

Now we can see the result 😏
final result

Full code:

<script lang="ts">
    import axios from 'axios';

    type User = {
        id: number;
        email: string;
        first_name: string;
        last_name: string;
        avatar: string;
    };

    type userData = {
        data: User[];
    };

    const getUsersData = async (url: string): Promise<User> => {
        const { data, status } = await axios.get<userData>(url);
        if (status === 200) {
            console.log(JSON.stringify(data.data));
            return data.data;
        } else {
            throw new Error('Something went wrong');
        }
    };

    const usersRespose = getUsersData("https://reqres.in/api/users");
</script>

{#await usersRespose}
    <p>...loading</p>
    {:then result}
        {#each result as user}
            <div class="user">
                <p>{user.id} - {user.first_name} {user.last_name}</p>
                <img src={user.avatar} alt={user.name}>
            </div>
        {/each}
    {:catch error}
        <p>Upps! {error}</p>
{/await}


<style>
    .user {
        display: flex;
        align-items: center;
        margin: 20px;
    }
    .user img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-left: 10px;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

And that's it, as you can see we have integrated TypeScript and SvelteKit in a single project, and immediately we see the benefits of both technologies, on the one hand a clearer and more readable JavaScript syntax with the static typing of TS and on the other hand all the advantages offered by Svelte to create web applications.

I hope this tutorial has helped you to integrate TS in your Svelte JS projects from now on. ✌🏻

Top comments (0)