MST
星途 面试题库

面试题:Vue 中如何在组件内使用 TypeScript 定义 prop 类型

请描述在 Vue 组件中,使用 TypeScript 定义 prop 类型的方法,并举例说明如何定义一个接收字符串类型且为必传的 prop。
21.6万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

在Vue组件中使用TypeScript定义prop类型,有以下几种常见方法:

  1. 使用PropType辅助类型

    import { defineComponent } from 'vue';
    import { PropType } from 'vue';
    
    interface User {
      name: string;
      age: number;
    }
    
    export default defineComponent({
      name: 'MyComponent',
      props: {
        // 定义接收字符串类型且必传的prop
        title: {
          type: String as PropType<string>,
          required: true
        },
        userInfo: {
          type: Object as PropType<User>,
          default: () => ({ name: '', age: 0 })
        }
      }
    });
    
  2. 使用接口定义props

    import { defineComponent } from 'vue';
    
    interface MyProps {
      title: string;
      count: number;
    }
    
    export default defineComponent({
      name: 'MyComponent',
      props: ['title', 'count'] as (keyof MyProps)[],
      setup(props: MyProps) {
        // 使用props
        return {};
      }
    });
    
  3. 使用defineProps宏(在单文件组件<script setup>中)

    <script setup lang="ts">
    const props = defineProps<{
      title: string;
      isVisible: boolean;
    }>();
    </script>
    

以定义一个接收字符串类型且为必传的prop为例,使用PropType的方式如下:

import { defineComponent } from 'vue';
import { PropType } from 'vue';

export default defineComponent({
  name: 'MyComponent',
  props: {
    message: {
      type: String as PropType<string>,
      required: true
    }
  }
});

<script setup>中使用defineProps宏的方式如下:

<script setup lang="ts">
const props = defineProps<{
  message: string;
}>();
</script>