一、报错 ‘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:‘快点来关注吧 ( ̄▽ ̄)"’)