TypeScript 是JS的一個超集,主要提供了型別系統和對ES6的支援,使用 TypeScript 可以增加程式碼的可讀性和可維護性,在 react 和 vue 社群中也越來越多人開始使用TypeScript。從最近釋出的 Vue3 正式版本來看, Vue3 的原始碼就是用 TypeScript 編寫的,更好TypeScript 支援也是這一次升級的亮點。當然,在實際開發中如何正確擁抱 TypeScript 也是遷移至 Vue3 的一個小痛點,這裡就針對 Vue3 和 TypeScript 展開一些交流。
96。8%的程式碼都是TypeScript,支援的力度也是相當大
專案搭建
在官方倉庫的 Quickstart 中推薦用兩種方式方式來構建我們的 SPA 專案:
vite
npm init vite-app sail-vue3 # OR yarn create vite-app sail-vue3
vue-cli
npm install -g @vue/cli # OR yarn global add @vue/cli vue create sail-vue3 # select vue 3 preset
vite 是一個由原生ESM驅動的Web開發構建工具,開啟 vite 依賴的 package。json 可以發現在 devDependencies 開發依賴裡面已經引入了TypeScript ,甚至還有 vuex , vue-router , less , sass 這些本地開發經常需要用到的工具。vite 輕量,開箱即用的特點,滿足了大部分開發場景的需求,作為快速啟動本地 Vue 專案來說,這是一個非常完美的工具。
後面的演示程式碼也是用vite搭的
從 vue2。x 走過來的掘友肯定知道 vue-cli 這個官方腳手架, vue3 的更新怎麼能少得了 vue-cli 呢, vue-cli 更強調的是用 cli 的方式進行互動式的配置,選擇起來更加靈活可控。豐富的官方外掛適配,GUI的建立管理介面,標準化開發流程,這些都是 vue-cli 的特點。
vue-cli TypeScript STEP1
vue-cli TypeScript STEP2
想要預裝TypeScript,就需要選擇手動配置,並check好TypeScript
忘記使用選擇 TypeScript 也沒事,加一行cli命令就行了
vue add typescript
最後,別忘了在 。vue 程式碼中,給 script 標籤加上
Option API風格
在 Vue2。x 使用過 TypeScript 的掘友肯定知道引入 TypeScript 不是一件簡單的事情:
要用 vue-class-component 強化 vue 元件,讓 Script 支援 TypeScript 裝飾器
用 vue-property-decorator 來增加更多結合 Vue 特性的裝飾器
引入 ts-loader 讓 webpack 識別 。ts 。tsx 檔案
。。。。。
然後出來的程式碼風格是這樣的:
@Component({ components:{ componentA, componentB}, }) export default class Parent extends Vue{ @Prop(Number) readonly propA!: number | undefined @Prop({ default: ‘default value’ }) readonly propB!: string @Prop([String, Boolean]) readonly propC!: string | boolean | undefined // data資訊 message = ‘Vue2 code style’ // 計算屬性 private get reversedMessage (): string[] { return this。message。split(‘ ’)。reverse()。join(‘’) } // method public changeMessage (): void { this。message = ‘Good bye’ } }
class 風格的元件,各種裝飾器穿插在程式碼中,有點感覺自己不是在寫 vue ,些許凌亂,所以這種曲線救國的方案在 vue3 裡面肯定是行不通的。
在 vue3 中可以直接這麼寫:
import { defineComponent, PropType } from ‘vue’ interface Student { name: string class: string age: number } const Component = defineComponent({ props: { success: { type: String }, callback: { type: Function as PropType<() => void> }, student: { type: Object as PropType
vue 對 props 進行復雜型別驗證的時候,就直接用 PropType 進行強制轉換, data 中返回的資料也能在不顯式定義型別的時候推斷出大多型別, computed 也只用返回型別的計算屬性即可,程式碼清晰,邏輯簡單,同時也保證了 vue 結構的完整性。
Composition API風格
在 vue3 的 Composition API 程式碼風格中,比較有代表性的api就是 ref 和 reactive ,我們看看這兩個是如何做型別宣告的:
ref
import { defineComponent, ref } from ‘vue’ const Component = defineComponent({ setup() { const year = ref(2020) const month = ref
分析上面的程式碼,可以發現如果我們不給定 ref 定義的型別的話, vue3 也能根據初始值來進行型別推導,然後需要指定複雜型別的時候簡單傳遞一個泛型即可。
Tips:如果只有setup方法的話,可以直接在defineComponent中傳入setup函式
const Component = defineComponent(() => { const year = ref(2020) const month = ref
reactive
import { defineComponent, reactive } from ‘vue’ interface Student { name: string class?: string age: number } export default defineComponent({ name: ‘HelloWorld’, setup() { const student = reactive
宣告 reactive 的時候就很推薦使用介面了,然後怎麼使用型別斷言就有很多種選擇了,這是 TypeScript 的語法糖,本質上都是一樣的。
自定義Hooks
vue3 借鑑 react hooks 開發出了 Composition API ,那麼也就意味著 Composition API 也能進行自定義封裝 hooks ,接下來我們就用 TypeScript 風格封裝一個計數器邏輯的 hooks ( useCount ):
首先來看看這個 hooks 怎麼使用:
import { ref } from ‘/@modules/vue’ import useCount from ‘。/useCount’ export default { name: ‘CountDemo’, props: { msg: String }, setup() { const { current: count, inc, dec, set, reset } = useCount(2, { min: 1, max: 15 }) const msg = ref(‘Demo useCount’) return { count, inc, dec, set, reset, msg } } }
出來的效果就是:
貼上 useCount 的原始碼:
import { ref, Ref, watch } from ‘vue’ interface Range { min?: number, max?: number } interface Result { current: Ref
分析原始碼
這裡首先是對 hooks 函式的入參型別和返回型別進行了定義,入參的 Range 和返回的 Result 分別用一個介面來指定,這樣做了以後,最大的好處就是在使用 useCount 函式的時候,ide就會自動提示哪些引數是必填項,各個引數的型別是什麼,防止業務邏輯出錯。
接下來,在增加 inc 和減少 dec 的兩個函式中增加了 typeo 型別守衛檢查,因為傳入的 delta 型別值在某些特定場景下不是很確定,比如在 template 中呼叫方法的話,型別檢查可能會失效,傳入的型別就是一個原生的 Event 。
關於 ref 型別值,這裡並沒有特別宣告型別,因為 vue3 會進行自動型別推導,但如果是複雜型別的話可以採用型別斷言的方式:ref(initObj) as Ref
小建議
AnyScript
在初期使用 TypeScript 的時候,很多掘友都很喜歡使用 any 型別,硬生生把TypeScript 寫成了 AnyScript ,雖然使用起來很方便,但是這就失去了 TypeScript 的型別檢查意義了,當然寫型別的習慣是需要慢慢去養成的,不用急於一時。
Vetur
vetur 程式碼檢查工具在寫vue程式碼的時候會非常有用,就像構建 vue 專案少不了 vue-cli 一樣,vetur 提供了 vscode 的外掛支援,趕著升級 vue3 這一波工作,順帶也把 vetur 也帶上吧。