【问题标题】:How to type a Generic component in Vue 3's <script setup>?如何在 Vue 3 的 <script setup> 中键入通用组件?
【发布时间】:2021-12-31 13:03:41
【问题描述】:

我有一个 Select 组件,它接受 options 的数组。每个option 可以是任何对象,只要它具有以下属性idtext

所以我是这样输入的:

type SelectOption<T> = {
  id: string | number
  text: string
} & T

但我不确定如何在组件中使用 definePropsdefineEmits

defineProps<{
  options: SelectOption<??>
  modelValue: SelectOption<??>
}>()

defineEmits<{
  (event: 'update:modelValue', SelectOption<??>): void
}>()

【问题讨论】:

    标签: typescript vuejs3 typescript-generics vue-composition-api


    【解决方案1】:

    如果您不关心其余键及其值,我建议您使用此选项。

    export type SelectOption = {
      id:   string;
      text: string;
      [key: string]: any;
    }
    //In setup composition api
    const props = defineProps({
        options: {
            type: Object as PropType<SelectOption>,
            required: true
        }
    })
    //Object driven
    props: {
        options: {
            type: Object as PropType<SelectOption>,
            required: true
        }
    }
    
    //In case of vue-class-component
    @Options({
        props: {
            /*...*/
      },
        emits: { /*...*/ },
    })
    

    你写的那个期望你在声明时提供一种类型。 这是一个例子:

    type Red<T> = {
       color: "red"
    } & T;
    
    type Wine = {
       ageYears: number,
       brand: string,
       origin: "France" | "Italy"
    }
    // for usage do this
    const redWine: Red<Wine> = {
       ageYears: 15,
       brand: "fancy brand",
       origin: "France",
       color: "red"
    }
    

    【讨论】:

    • 投了反对票的人。你能解释一下为什么吗?以及您如何不觉得这很有用。
    • 我没有投反对票,但您根本没有回答问题。通用道具的用例很广泛,目的不是(引用你)to provide a type when declared。泛型的想法是,您不需要事先确切知道传递的类型,但打字稿可以推迟它,然后用它做一些事情。使用带有any 的动态记录不会取代泛型,因为您无法获得任何类型安全性(想象一个接收特定类型数据的表,以及需要键的其他一些道具(例如表上的sorting 数组)根据提供的数据。
    猜你喜欢
    • 2022-09-25
    • 2022-08-09
    • 2021-10-27
    • 2021-11-13
    • 2021-01-07
    • 2020-12-05
    • 2021-09-23
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多