vue2.x+ts项目,在props type导入自定义接口类型报‘xxx‘ only refers to a type, but is being used as a value here处理办法

本文介绍了解决在Vue项目中使用自定义类型作为Props时出现的类型报错问题,并提供了一种通过类型断言的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、报错 ‘xxx’ only refers to a type, but is being used as a value here

在Props中使用自定义类型约束时,报上面的错误。然后 我在网上查找教程,找到一个说在ts中导出class 接口,虽然没有报错,但是按照我的下面的定义,在父组件中传入data值,会报错误。那如何改动呐?

export class popType {
  title: {
    name: string;
    nameStyle?: style;
  };
  content: {
    text: string;
    textStyle?: style;
  };
  confirmButton?:{
      open:boolean,
      text:string,
      textStyle?: style;
  }
}

在这里插入图片描述

二、使用 as来完成改动

在vscode中通过ctrl+鼠标左键找到了props的声明文件,在声明文件中,type的声明如下

export interface PropOptions<T=any> {
  type?: PropType<T>;
  required?: boolean;
  default?: T | null | undefined | (() => T | null | undefined);
  validator?(value: T): boolean;
}
export type PropType<T> = Prop<T> | Prop<T>[];
export type Prop<T> = { (): T } | { new(...args: never[]): T & object } | { new(...args: string[]): Function }
由上面可以知道type的类型,必须是这样{ (): T } | { new(...args: never[]): T & object } | { new(...args: string[]): Function },所以我们平时定义的
export interface popType {
  title: {
    name: string;
    nameStyle?: style;
  };
  }
  这样的接口是不行的(不是函数类型),所以会报错,这也是为什么网上会有人说把export interface popType{},改为export class popType{},就能通过

知道了原理,让我们改一下文件

import { PropType } from 'vue';
import { popType } from './type/popType';//自己定义的类型

popData: {
      type: Object as PropType<popType>,//断言
      default: () => {
        return {
          title: {
            name: '无',
            nameStyle: {
              textAlign: 'center',
              fontSize: 16,
              color: '#333',
              fontFamily: 'PingFangSC-Semibold',
              margin: 'auto'
            }
          },
          content: {
            text:'无',
            textStyle: {
              textAlign: 'left',
              fontSize: 16,
              color: '#333',
              fontFamily: 'PingFangSC-Semibold',
              margin: '0'
            }
          },
          confirmButton: {
            open: false
          }
        };
      }
    }

这样就在使用中就不会报错了

如果有问题,欢迎指出
ps:欢迎大家关注(内心os:‘快点来关注吧 ( ̄▽ ̄)"’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kinghiee

助力蛋白粉计划

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值