在本教程中
attributeChangedCallback
是这样实现的:
// attribute change
attributeChangedCallback(property, oldValue, newValue) {
if (oldValue === newValue) return;
this[ property ] = newValue;
}
我正在尝试将其转换为 Typescript,到目前为止我有这个:
// attribute change
attributeChangedCallback(property:keyof HelloWorldComponent, oldValue:any, newValue:any) {
if (oldValue === newValue) return;
this[ property ] = newValue;
}
}
但是这仍然会产生错误:
Cannot assign to 'ATTRIBUTE_NODE' because it is a read-only property.ts(2540)
Cannot assign to 'CDATA_SECTION_NODE' because it is a read-only property.ts(2540)
Cannot assign to 'COMMENT_NODE' because it is a read-only property.ts(2540)
Cannot assign to 'DOCUMENT_FRAGMENT_NODE' because it is a read-only property.ts(2540)
Cannot assign to 'DOCUMENT_NODE' because it is a read-only property.ts(2540)
想法?
您似乎正在尝试分配给只读属性 当 Typescript 无法正确推断属性参数的类型时,它始终默认为包含只读属性的类型
这是一个更好的解决方案
class HelloWorldComponent extends HTMLElement {
private attr1: string | null = null;
private attr2: string | null = null;
attributeChangedCallback(property: string, oldValue: string | null, newValue: string | null) {
if (oldValue === newValue) return;
switch (property) {
case 'attr1':
this.attr1 = newValue;
break;
case 'attr2':
this.attr2 = newValue;
break;
// Handle other attributes if needed
default:
throw new Error(`Unhandled attribute: ${property}`);
}
}
}