How to use Typescript in Vue

Typescript Type Fundamentals

What is a type?

//javascript
let food = 'sushi'
let code = ['js','python'']
let music = {
    year: 1996
    mood: 'happy',
    genres: ['country', 'blues', 'jazz'],
}

// typescript
let food: string = 'sushi'
let code: string[] = ['js','python'']
let music: {
    year: number; // semicolon ended
    mood: string; // small cap, e.g string not String
    genres: string[];
} = {
    year: 1996,
    mood: 'happy',
    genres: ['country', 'blues', 'jazz'],
} 

For typing object, better useinterface

What is interface?

interface Music {
    year: number
    mood: string
    genres: string[]
}
            πŸ‘‡
let music: Music = {
    year: 2022
    mood: 'energetic',
    genres: ['electronic', 'classical'],
}

or use together mixing withtype

type moodType = 'happy' | 'energetic'

interface Music {
    year: number
    mood: moodType πŸ‘ˆ // 'happy' or 'energetic'
    genres: string[]
}

Typeparamorreturn valuefor Function (computed property or method in Vue)

// js
function sum(num1, num2){
    return num1 + num2
}

//ts, accept number, return number
function sum(n1: number, n2: number): number{
    return n1 + n2
}

How to use Typescript in Vue?

change

<script>
export default {
    name: 'BaseButton',
    .
    .
}
</script>

to

           πŸ‘‡
<script lang='ts'>
import { defineComponent } from 'vue'
export default defineComponent({ πŸ‘ˆ
    name: 'BaseButton',
    .
    .
})
</script>

Props Typing

UseGenericin Typescript and vue helper methodPropType

import { defineComponent, PropType } from 'vue'
import { EventItem } from '../types'

export default defineComponent({
    props: {
        event: {
            type: PropType<EventItem>, πŸ‘ˆ
            required: true
        }
    }
})

That’s it. ✨

Made with❀by leovoon