TepeScript 问题记录

  1. 问题 对object的所有属性赋值或清空,提示类型错误不能赋值
type VoiceParams = {
    _id?: string | undefined;
    name: string;
    sex: string;
    vc_id: string;
    model_url: string;
    preview_url: string;
    isPrivate: boolean;
    visible: boolean;
}

const formData = reactive<VoiceParams>({
	_id: '',
	name: '',
	sex: '',
	vc_id: '',
	model_url: '',
	preview_url: '',
	isPrivate: true,
	visible: false,
});

const editVoice = async (row: VoiceParams | null) => {
	dialogVisible.value = true;
	if (row) {
		for (const key in formData) {
			if (Object.prototype.hasOwnProperty.call(formData, key)) {
				// formData[key] = row[key]; // 将表单中的值复制
				formData[key] = row[key];
			}
		}
	}
};

报ts错误
row[key]上提示

(parameter) row: VoiceParams
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'VoiceParams'.
  No index signature with a parameter of type 'string' was found on type 'VoiceParams'.ts(7053)

formData[key] 上提示

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ _id?: string | undefined; name: string; sex: string; vc_id: string; model_url: string; preview_url: string; isPrivate: boolean; visible: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ _id?: string | undefined; name: string; sex: string; vc_id: string; model_url: string; preview_url: string; isPrivate: boolean; visible: boolean; }'.ts(7053)

报错信息

  1. 解决
    找了好些地方,都没搞定,chatgpt都…
const editVoice = async (row: VoiceParams | null) => {
	dialogVisible.value = true;
	if (row) {
		for (const key in formData) {
			if (Object.prototype.hasOwnProperty.call(formData, key)) {
				const validKey = key as keyof VoiceParams;
				// 非string类型 单独赋值
				if (validKey === '_id') formData['_id'] = row['_id'];
				else if (validKey === 'isPrivate') formData['isPrivate'] = row['isPrivate'];
				else if (validKey === 'visible') formData['visible'] = row['visible'];
				else formData[validKey] = row[validKey];
			}
		}
	}
};

// 监听新增编辑弹框
watch(
	() => dialogVisible.value,
	(val) => {
		if (!val) {
			// 清空表单
			for (const key in formData) {
			if (Object.prototype.hasOwnProperty.call(formData, key)) {
				// 将表单中的值重置为初始状态
				const validKey = key as keyof VoiceParams;
					if (validKey === 'isPrivate') formData['isPrivate'] = true;
					else if (validKey === 'visible') formData['visible'] = false;
					else formData[validKey] = '';
			}
		}
		}
	}
);

重点:非string类型 单独赋值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值