TypeScript 支持
TypeScript 支持
Vue CLI 提供内置的 TypeScript 工具支持。
NPM 包中的官方声明
随着应用的增长,静态类型系统可以帮助防止许多潜在的运行时错误,这就是为什么 Vue 3 是用 TypeScript 编写的。这意味着在 Vue 中使用 TypeScript 不需要任何其他工具——它具有一等公民支持。
推荐配置
// tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
// 这样就可以对 `this` 上的数据属性进行更严格的推断
"strict": true,
"jsx": "preserve",
"moduleResolution": "node"
}
}
请注意,必须包含 strict: true (或至少包含 noImplicitThis: true,它是 strict 标志的一部分) 才能在组件方法中利用 this 的类型检查,否则它总是被视为 any 类型。 参见 TypeScript 编译选项文档查看更多细节。
Webpack 配置
如果你使用自定义 Webpack 配置,需要配置 ts-loader 来解析 vue 文件里的 <script lang="ts">
代码块:
// webpack.config.js
module.exports = {
...
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/],
},
exclude: /node_modules/,
},
{
test: /\.vue$/,
loader: 'vue-loader',
}
...
开发工具
项目创建
Vue CLI 可以生成使用 TypeScript 的新项目,开始:
# 1. Install Vue CLI, 如果尚未安装
npm install --global @vue/cli@next
# 2. 创建一个新项目, 选择 "Manually select features" 选项
vue create my-project-name
# 3. 如果已经有一个不存在TypeScript的 Vue CLI项目,请添加适当的 Vue CLI插件:
vue add typescript
请确保组件的 script 部分已将语言设置为 TypeScript:
<script lang="ts">
...
</script>
或者,如果你想将 TypeScript 与 JSX render 函数结合起来:
<script lang="tsx">
...
</script>
编辑器支持
对于使用 TypeScript 开发 Vue 应用程序,我们强烈建议使用 Visual Studio Code,它为 TypeScript 提供了很好的开箱即用支持。如果你使用的是单文件组件 (SFCs),那么可以使用很棒的 Volar extension,它在 SFCs 中提供了 TypeScript 推理和许多其他优秀的特性。
WebStorm 同时为 TypeScript 和 Vue 提供内置的支持。其它的 JetBrains IDE 对它们也通过内置或免费插件的方式进行支持。
定义 Vue 组件
要让 TypeScript 正确推断 Vue 组件选项中的类型,需要使用 defineComponent 全局方法定义组件:
import { defineComponent } from 'vue'
const Component = defineComponent({
// 已启用类型推断
})
如果你使用的是单文件组件,则通常会被写成:
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
// 已启用类型推断
})
</script>
与 Options API 一起使用
TypeScript 应该能够在不显式定义类型的情况下推断大多数类型。例如,对于拥有一个数字类型的 count property 的组件来说,如果你试图对其调用字符串独有的方法,会出现错误:
const Component = defineComponent({
data() {
return {
count: 0
}
},
mounted() {
const result = this.count.split('') // => Property 'split' does not exist on type 'number'
}
})
如果你有一个复杂的类型或接口,你可以使用 type assertion 对其进行指明:
interface Book {
title: string
author: string
year: number
}
const Component = defineComponent({
data() {
return {
book: {
title: 'Vue 3 Guide',
author: 'Vue Team',
year: 2020
} as Book
}
}
})
为 globalProperties 扩充类型
Vue 3 提供了一个 globalProperties 对象,用来添加可以被任意组件实例访问的全局 property。例如一个插件想要注入一个共享全局对象或函数。
// 用户定义
import axios from 'axios'
const app = Vue.createApp({})
app.config.globalProperties.$http = axios
// 验证数据的插件
export default {
install(app, options) {
app.config.globalProperties.$validate = (data: object, rule: object) => {
// 检查对象是否合规
}
}
}
为了告诉 TypeScript 这些新 property,我们可以使用模块扩充 (module augmentation)。
在上述示例中,我们可以添加以下类型声明:
import axios from 'axios'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$http: typeof axios
$validate: (data: object, rule: object) => boolean
}
}
我们可以把这些类型声明放在同一个文件里,或一个项目级别的 *.d.ts 文件 (例如在 TypeScript 会自动加载的 src/typings 文件夹中)。对于库/插件作者来说,这个文件应该被定义在 package.json 的 types property 里。
注意
确认声明文件是一个 TypeScript 模块
为了利用好模块扩充,你需要确认你的文件中至少有一个顶级的 import 或 export,哪怕只是一个 export {}。
在 TypeScript 中,任何包含一个顶级 import 或 export 的文件都被视为一个“模块”。如果类型声明在模块之外,该声明会覆盖而不是扩充原本的类型。
关于 ComponentCustomProperties 类型的更多信息,请参阅其在 @vue/runtime-core 中的定义及其 TypeScript 测试用例学习更多。
注解返回类型
由于 Vue 声明文件的循环特性,TypeScript 可能难以推断 computed 的类型。因此,你可能需要注解计算属性的返回类型。
import { defineComponent } from 'vue'
const Component = defineComponent({
data() {
return {
message: 'Hello!'
}
},
computed: {
// 需要注解
greeting(): string {
return this.message + '!'
},
// 在使用 setter 进行计算时,需要对 getter 进行注解
greetingUppercased: {
get(): string {
return this.greeting.toUpperCase()
},
set(newValue: string) {
this.message = newValue.toUpperCase()
}
}
}
})
注解 Props
Vue 对定义了 type 的 prop 执行运行时验证。要将这些类型提供给 TypeScript,我们需要使用 PropType 指明构造函数:
import { defineComponent, PropType } from 'vue'
interface Book {
title: string
author: string
year: number
}
const Component = defineComponent({
props: {
name: String,
id: [Number, String],
success: { type: String },
callback: {
type: Function as PropType<() => void>
},
book: {
type: Object as PropType<Book>,
required: true
},
metadata: {
type: null // metadata 的类型是 any
}
}
})
注意
由于 TypeScript 中的设计限制,当它涉及到为了对函数表达式进行类型推理,你必须注意对象和数组的 validator 和 default 值:
import { defineComponent, PropType } from 'vue'
interface Book {
title: string
year?: number
}
const Component = defineComponent({
props: {
bookA: {
type: Object as PropType<Book>,
// 请务必使用箭头函数
default: () => ({
title: 'Arrow Function Expression'
}),
validator: (book: Book) => !!book.title
},
bookB: {
type: Object as PropType<Book>,
// 或者提供一个明确的 this 参数
default(this: void) {
return {
title: 'Function Expression'
}
},
validator(this: void, book: Book) {
return !!book.title
}
}
}
})
注解 emit
我们可以为触发的事件注解一个有效载荷。另外,所有未声明的触发事件在调用时都会抛出一个类型错误。