• TypeScript 与组合式 API


    TypeScript 与组合式 API

    一、为组件的 props 标注类型

    1.1 使用
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    语法限制

    为了生成正确的运行时代码,传给 defineProps() 的泛型参数必须是以下之一:

    • 一个类型字面量:
    defineProps<{ /*... */ }>()
    
    • 1
    • 同一个文件中的一个接口或对象类型字面量的引用:
    interface Props {/* ... */}
    
    defineProps<Props>()
    
    • 1
    • 2
    • 3

    接口或对象字面类型可以包含从其他文件导入的类型引用,但是,传递给 defineProps 的泛型参数本身不能是一个导入的类型:

    import { Props } from './other-file'
    
    // 不支持!
    defineProps<Props>()
    
    • 1
    • 2
    • 3
    • 4

    这是因为 Vue 组件是单独编译的,编译器目前不会抓取导入的文件以分析源类型。我们计划在未来的版本中解决这个限制。

    1.2 Props 解构默认值

    当使用基于类型的声明时,我们失去了对 props 定义默认值的能力。这可以通过目前实验性的响应性语法糖来解决:

    <script setup lang="ts">
    interface Props {
      foo: string
      bar?: number
    }
    
    // 对 defineProps() 的响应性解构
    // 默认值会被编译为等价的运行时选项
    const { foo, bar = 100 } = defineProps<Props>()
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这个行为目前需要显式地选择开启

    1.3 非