關於TypeScript 泛型入門與實踐,網上有不少文章但大多缺乏實戰經驗。本文結合真實專案,探討最佳實踐。
快速上手
下面是一個實際的例子:
javascript
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash:8].js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors'
}
}
}
},
plugins: [
new HtmlWebpackPlugin({ template: './src/index.html' }),
new MiniCssExtractPlugin({ filename: '[name].css' })
]
}
這種模式在團隊中推廣後效果很好,維護成本明顯降低。
高階用法
我們可以通過以下方式實現:
javascript
const { sum, debounce } = require('./utils')
describe('utils', () => {
test('sum 計算正確', () => {
expect(sum(1, 2)).toBe(3)
expect(sum(-1, 1)).toBe(0)
})
test('debounce 延遲執行', () => {
jest.useFakeTimers()
const fn = jest.fn()
const debounced = debounce(fn, 300)
debounced()
debounced()
debounced()
expect(fn).not.toHaveBeenCalled()
jest.advanceTimersByTime(300)
expect(fn).toHaveBeenCalledTimes(1)
})
})
注意上面程式碼中的效能細節,避免不必要的計算。
業務場景
具體實現參考以下程式碼:
javascript
{% raw %}
<template>
<div>
<p>{{ message }}</p>
<button @click="reverse">反轉</button>
</div>
</template>
<script>
export default {
data() {
return { message: 'Hello Vue 2' }
},
methods: {
reverse() {
this.message = this.message.split('').reverse().join('')
}
}
}
</script>
{% endraw %}
經過線上驗證,這套方案執行穩定。
避坑指南
先來看基本的用法:
javascript
export default {
props: ['items'],
computed: {
sorted() {
return [...this.items].sort((a, b) => b.score - a.score)
},
count() {
return this.items.length
}
},
filters: {
formatDate(val) {
return new Date(val).toLocaleDateString('zh-CN')
}
}
}
這種寫法簡潔明瞭,適合大多數場景。
快速上手
核心程式碼如下:
javascript
export default {
directives: {
focus: {
inserted(el) {
el.focus()
}
},
loading: {
bind(el, binding) {
if (binding.value) {
el.classList.add('loading')
}
},
update(el, binding) {
el.classList.toggle('loading', binding.value)
}
}
}
}
實際專案中還需要考慮邊界條件和異常處理。
小結
- 團隊中統一約定比追求完美實現更重要
- 持續學習和總結,保持技術敏感度
- 遇到問題多看原始碼和官方文件