工具类型 {#utility-types}

:::info 本页文档罗列出了一部分可能需要解释一下使用方式的常用工具类型。若要获取这些工具类型的完整列表,请查看源代码。 :::

PropType\ {#proptypet}

在定义运行时 props 时用更高阶的类型定义来标注一个 prop。

  • 示例

    1. import { PropType } from 'vue'
    2. interface Book {
    3. title: string
    4. author: string
    5. year: number
    6. }
    7. export default {
    8. props: {
    9. book: {
    10. // 提供一个比 `Object` 更具体的类型
    11. type: Object as PropType<Book>,
    12. required: true
    13. }
    14. }
    15. }
  • 相关内容: 指南 - 为组件 props 标注类型

ComponentCustomProperties {#componentcustomproperties}

用于增强组件实例类型以支持自定义全局属性。

  • 示例

    1. import axios from 'axios'
    2. declare module 'vue' {
    3. interface ComponentCustomProperties {
    4. $http: typeof axios
    5. $translate: (key: string) => string
    6. }
    7. }

    :::tip 类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看 类型扩充指南 了解更多细节 :::

  • 相关内容: 指南 - 扩充全局属性

ComponentCustomOptions {#componentcustomoptions}

用来扩充组件选项类型以支持自定义选项。

  • 示例

    1. import { Route } from 'vue-router'
    2. declare module 'vue' {
    3. interface ComponentCustomOptions {
    4. beforeRouteEnter?(to: any, from: any, next: () => void): void
    5. }
    6. }

    :::tip 类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看 类型扩充指南 了解更多细节。 :::

  • 相关内容: 指南 - 扩充自定义选项

ComponentCustomProps {#componentcustomprops}

用于扩充允许的TSX prop,以便在 TSX 元素上使用没有在组件选项上定义过的 prop。

  • 示例

    1. declare module 'vue' {
    2. interface ComponentCustomProps {
    3. hello?: string
    4. }
    5. }
    6. export {}
    1. // 现在即使没有在组件选项上定义过 hello 这个 prop 也依然能通过类型检查了
    2. <MyComponent hello="world" />

    :::tip 类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看 类型扩充指南 了解更多细节。 :::

CSSProperties {#cssproperties}

用于扩充在样式属性绑定上允许的值的类型。

  • 示例

    允许任意自定义 CSS 属性:

    ```ts declare module ‘vue’ { interface CSSProperties {

  1. [key: `--${string}`]: string
  2. }

}

  1. ```tsx
  2. <div style={ { '--bg-color': 'blue' } }>
  1. <div :style="{ '--bg-color': 'blue' }">

:::tip 类型扩充必须被放置在一个模块 .ts.d.ts 文件中。查看 类型扩充指南 了解更多细节。 :::

:::info 相关内容 SFC <style> 标签支持通过 v-bind:CSS 函数来链接 CSS 值与组件状态。这允许在没有类型扩充的情况下自定义属性。