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
- Choose to use a skeleton project. And follow the next steps:
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:
<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
{
"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
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
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:
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}
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>
Now we can see the 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>
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)