English 中文(简体)
如何说明 通用模板中两种类型之间的关系
原标题:How to tell Vue typescript parser the relationship between two types in a generic template

我正试图在Vue 3.4建立一个通用模板,处理在一页上显示外地的情况。 我有描述相关变量的描述类型:

export enum FieldType {
  Text,
  Checkbox,
} 

export type FieldDescription<T extends FieldType> = {
  label: string,
  type: T,
}

export type FieldComponentModelType<T extends FieldType> =
  T extends FieldType.Text ? string :
  T extends FieldType.Checkbox ? boolean :
  never;

我当时正试图建立这样的通用模板:

<template>
  <TextField v-if="props.field.type===FieldType.Text"
    v-model="model"
    :label="props.field.label"
  />
  <CheckField v-if="props.field.type===FieldType.Checkbox"
    v-model="model"
    :label="props.field.label"
  />
</template>

<script setup lang="ts" generic="T extends FieldType">  
  const props = defineProps({
    field: {
      type: Object as PropType<FieldDescription<T>>,
      required: true,
    },
  });

  const model = defineModel<FieldComponentModelType<T>>({ required: true });
</script>

该公司进行细微工作,但在模板中的试样转让上,我发现一个字面错误:Type string string OHean不能被分配到打字(或核对箱案则相反)。 我认为,所发生的情况是,只有T是文本,才能看到文本现场的标记,因此模型必须是一种扼杀(例如,由外地协调委员会负责的ModelType<外勤人员)。 案文和案文;正在说明。

是否有某种办法可加以证明以避免错误? 或者,我顺便说一说,只是说它忽略了错误?

问题回答

你们可以这样做,并且应该不出现任何错误。

<template>
  <TextField v-if="props.field.type === FieldType.Text"
    v-model="model"
    :label="props.field.label"
  />
  <CheckField v-else-if="props.field.type === FieldType.Checkbox"
    v-model="model"
    :label="props.field.label"
  />
</template>

<script setup lang="ts">
import { defineProps, defineModel } from  vue ;
import { FieldType, FieldDescription, FieldComponentModelType } from  ./types ;

const props = defineProps<{
  field: FieldDescription<FieldType>
}>();

// Define model type based on field type
type ModelType = FieldType extends FieldType.Text ? string :
                 FieldType extends FieldType.Checkbox ? boolean :
                 never;

const model = defineModel<ModelType>({ required: true });
</script>

这涉及根据<代码> 外地标准对适当外地部分的有条件提供,并用从外地类型推断的正确类型界定了<代码>model。





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签