ref<number>(0) 泛型"> ref<number>(0) 泛型"> ref<number>(0) 泛型">
TypeScript 词条目录
前端Wiki/TypeScript/实战/框架实战与排错

Vue 中写 TypeScript

Vue 3 的Composition API 天然与 TS 契合:ref<number>(0) 泛型指定值类型,reactive 自动按对象推断;defineProps<T> 直接用类型字面量声明 props,编译宏不需要引入。

建议用 <script setup lang="ts">:props/emits/expose 都有类型推导。组件实例类型取 InstanceType<typeof MyComp>,配合 ref 拿到带类型的方法句柄。

  • ref(init):泛型指定值类型;reactive 按初始值自动推断
  • defineProps() / defineEmits():编译宏,类型字面量直接写
  • 组件实例类型:InstanceType 配合 ref 使用
TS
<!-- UserCard.vue -->
<script setup lang="ts">
import { ref } from 'vue';

// 泛型写法:明确值类型
const count = ref<number>(0);
const name = ref('小明');       // 自动推断 Ref<string>

// props 用类型字面量声明
const props = defineProps<{
  id: number;
  tags?: string[];              // 可选 prop
}>();

// emits 照样有类型
const emit = defineEmits<{
  (e: 'update', id: number): void;
}>();

function inc() {
  count.value++;
  emit('update', props.id);
}
</script>
JS
// script setup 编译后:泛型擦除,宏变运行时代码
import { ref } from 'vue';
export default {
  props: { id: Number, tags: Array },   // 运行时仍需要真实 props 声明
  emits: ['update'],
  setup(props, { emit }) {
    const count = ref(0);
    const name = ref('小明');
    function inc() {
      count.value++;
      emit('update', props.id);
    }
    return { count, name, inc };
  },
};
本节要点Vue3 + script setup:ref 泛型、defineProps() 类型字面量,TS 体验一路推导。