- 问题 对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)
- 解决
找了好些地方,都没搞定,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类型 单独赋值