In every frontend, almost every line of code is written in TypeScript.
Component sample
We’ll write the following component in Vue2, Vue3, React and Svelte + TypeScript.
Vue2 - Using Class Components
If you want to use TypeScript or if you don’t want to code your components with the Vue2 options API, you can configure your them as Class Components using vue-class-component
and vue-property-decorator
.
SampleVue2.vue
<template>
<div>
<ButtonPrimary @click="increment(1)">Counter: {{ counter }}</ButtonPrimary>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import ButtonPrimary from "@/components/ui/buttons/ButtonPrimary.vue";
@Component({
components: {
ButtonPrimary
}
})
export default class SampleComponent extends Vue {
counter = 0;
mounted() {
console.log("mounted")
}
increment(i: number) {
this.counter += i;
}
}
</script>
Vue3
Vue 3 is written in TypeScript, so no additional tooling is required in order to use TypeScript.SampleVue3.vue
<template>
<div>
<ButtonPrimary @click="increment(1)">Counter: {{ counter }}</ButtonPrimary>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import ButtonPrimary from '@/components/ui/buttons/ButtonPrimary.vue';
const counter = ref(0);
onMounted(() => {
console.log("mouted")
})
function increment(i: number) {
counter.value += i;
}
</script>
React
Almost every component is written in .tsx
files, so 99% is type-safe.
SampleReact.tsx
import { useEffect, useState } from "react";
import ButtonPrimary from "@/components/ui/buttons/ButtonPrimary";
export default function SampleComponent() {
const [counter, setCounter] = useState(0);
useEffect(() => {
console.log("mounted");
}, []);
function increment(i: number) {
setCounter(counter + i);
}
return (
<div>
<ButtonPrimary onClick={() => increment(1)}>Counter: {counter}</ButtonPrimary>
</div>
);
}
Svelte
Svelte also supports TypeScript without any additional tooling.
SampleSvelte.svelte
<script lang="ts">
import { onMount } from "svelte";
import ButtonPrimary from "@/components/ui/buttons/ButtonPrimary.svelte";
let counter: number = 0;
onMount(() => {
console.log("mounted");
});
function increment(i: number) {
counter += i;
}
</script>
<div>
<ButtonPrimary on:click={() => increment(1)}>Counter: {counter}</ButtonPrimary>
</div>