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[]
}
Typeparam
orreturn value
for 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