IDE 支持
- Volar 是官方的 VSCode 扩展,提供了 Vue 单文件组件中的 TypeScript 支持,还伴随着一些其他非常棒的特性。
- TypeScript Vue Plugin 用于支持在 TS 中 import *.vue 文件。
配置 tsconfig.json
通过 create-vue 搭建的项目包含了预先配置好的 tsconfig.json。
手动配置 tsconfig.json 时,请留意以下选项:
- compilerOptions.isolatedModules 应当设置为 true,因为 Vite 使用 esbuild 来转译 TypeScript,并受限于单文件转译的限制。
- 如果你在构建工具中配置了路径解析别名,例如 @/* 这个别名被默认配置在了 create-vue 项目中,你需要通过 compilerOptions.paths 选项为 TypeScript 再配置一遍。
Volar Takeover 模式
在每个项目里我们都运行了两个语言服务实例:一个来自 Volar,一个来自 VSCode 的内置服务。这在大型项目里可能会带来一些性能问题。为了优化性能,Volar 提供了一个叫做“Takeover 模式”的功能。在这个模式下,Volar 能够使用一个 TS 语言服务实例同时为 Vue 和 TS 文件提供支持
- 在当前项目的工作空间下,用 Ctrl + Shift + P (macOS:Cmd + Shift + P) 唤起命令面板。
- 输入 built,然后选择“Extensions:Show Built-in Extensions”。
- 在插件搜索框内输入 typescript (不要删除 @builtin 前缀)。
- 点击“TypeScript and JavaScript Language Features”右下角的小齿轮,然后选择“Disable (Workspace)”。
- 重新加载工作空间。Takeover 模式将会在你打开一个 Vue 或者 TS 文件时自动启用。
defineComponent()
为了让 TypeScript 正确地推导出组件选项内的类型,我们需要通过 defineComponent() 这个全局 API 来定义组件
import {
defineComponent } from 'vue'
export default defineComponent({
// 启用了类型推导
props: {
message: String
},
setup(props) {
props.message // 类型:string | undefined
}
})
为组件的 props 标注类型
为了生成正确的运行时代码,传给 defineProps() 的泛型参数必须是以下之一:
- defineProps<{ /*… */ }>()
- interface Props {/* … */} defineProps()
<script setup lang="ts">
const props = defineProps<{
foo: string
bar?: number
}>()
</script>
<script setup lang="ts">
interface Props {
foo: string
bar?: number
}
const props = defineProps<Props>()
</script>
withDefaults 编译器
为 props 声明默认值的能力。这可以通过 withDefaults 编译器宏解决:
export interface