Getting Started with SvelteKit and TypeScript
Tags: typescript, svelte, webdev
Published: 2022-07-30 17:53:00

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**](https://nodejs.org/es/) installed on your machine_

First, let's generate a new SvelteKit project
```
npm create svelte@latest my-project-name
```
* Choose to use a skeleton project.
And follow the next steps:
![first step](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqqs4f1qufk4mdrzmxxk.png)
![Second step](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6fw1qq085h2dojs1y85.png)
 
Now go to your project folder:
```
cd my-project-name
```
```
npm install
```
```
//to actively check for TS errors in our code runs
npm run check:watch
```
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:
```js 
  <script lang="ts">

  </script> 
```
> 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
```json 
  {
      "id": 1,
      "email": "George.@example.com",
      "first_name": "George",
      "last_name": "Bluth",
      "avatar": "https://reqres.in/img/faces/1-image.jpg"
  } 
```

The first thing we will do is to define a TS interface and a function to fetch from the API
```js 
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
}
```
Let's complete our function
```js 
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");
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7xvucilvmhoc94xn5zzy.png)

Now we just need to display this data in our HTML 👌Let's see how this would work in Svelte: 
```js
{#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}
```
Let's add a bit of CSS to style the result: 
```css
<style>
    .user {
        display: flex;
        align-items: center;
        margin: 20px;
    }
    .user img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-left: 10px;
    }
</style>
```

Now we can see the result 😏
![final result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fpjn8ibgr92hwivcuvc.png)

**Full code:**
```js
<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>
```

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.  ✌🏻