TypeScript 怎么把 vue 中的一个类型简写为一个全局的类型?

现在是这样的

<template>
    <Form ref="formRef" />
</template>

<script lang="ts" setup>
import { UnwrapRef } from 'vue';
import { RefValue } from 'vue/macros';
import Form from './Form.vue';

let formRef: RefValue<UnwrapRef<InstanceType<typeof Form>>> = $ref();
</script>

我想要的

<template>
    <Form ref="formRef" />
</template>

<script lang="ts" setup>
import Form from './Form.vue';

let formRef: UnRef<Form> = $ref();

怎么在env.d.ts中定义全局类型,而不用每次使用都要引入

import { UnwrapRef } from 'vue';
import { RefValue } from 'vue/macros';

type UnRef<T> = RefValue<UnwrapRef<InstanceType<typeof T>>>

因为这里使用了import,就不是全局的了。怎么做到定义全局呢?


更新:

// 定义global.d.ts
import { UnwrapRef, VueElementConstructor } from 'vue';
import { RefValue } from 'vue/macros';

declare global {
  type UnRef<T extends VueElementConstructor<any>> = RefValue<UnwrapRef<InstanceType<T>>>;
}

// 使用
import Form from './Form.vue';
let formRef: UnRef<typeof Form> = $ref();
阅读 2.4k
2 个回答
declare global {
    type UnRef<T> = RefValue<UnwrapRef<InstanceType<typeof T>>>
}

使用: declare global

import { UnwrapRef } from 'vue';
import { RefValue } from 'vue/macros';
declare global {
    type UnRef<T> = RefValue<UnwrapRef<InstanceType<typeof T>>>
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题