ts进阶场景使用
1、vue中 为组件模板引用标注类型
<!-- App.vue -->
<script setup lang="ts">
import MyModal from './MyModal.vue'
const modal = ref<InstanceType<typeof MyModal> | null>(null)
const openModal = () => {
modal.value?.open()
}
</script>
- typeof 获取值的类型
- InstanceType 获取类的实例类型
2、三斜线指令
在vite项目里看到 /// <reference types="vite/client" />
- path 用于声明对另一个文件的依赖
- types 用于声明对另外一个库的依赖
- lib 用于声明对内置库的依赖
3、实现单例模式,通过类 + 静态成员
class Board {
width: number = 500
height: number = 700
init() {
console.log('初始化棋盘')
}
private constructor() {}
private static _board:Board
static createBoard(): Board {
if (this._board) {
return this._board
}
this._board = new Board()
return this._board
}
}
const b1 = Board.createBoard()
const b2 = Board.createBoard()
console.log(b1 === b2) // true
...日常工作中使用到再继续补充