How to properly read arbitrary element props? #16706
-
| I updated the global HTMLAttributes interface to add a property like so => declare global {
  namespace svelteHTML {
    interface HTMLAttributes<T> {
      test?: () => void;
    }
  }
}Now I was hoping to access and read this like element.test after getting a reference to the element, but element.test is undefined; | 
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
| If you set an unknown attribute/property, Svelte will compile that to just setting an attribute on the element, so there is no supported way of doing that. I also would not recommend it; mixing standardized attributes with arbitrary custom properties is likely to just cause confusion. I would probably use an attachment and a  <script>
	import { fn } from './fn.js';
	let div;
	$effect(() => {
		fn.for(div)();
	});
</script>
<div
	bind:this={div}
	{@attach fn(() => console.log('Attached function called'))}>
	An element
</div>// fn.js
const map = new Map();
export const fn = value => node => {
	map.set(node, value);
	return () => map.delete(node);
};
fn.for = node => map.get(node); | 
Beta Was this translation helpful? Give feedback.
Those are internals which can break at any point, so I would not recommend that.
You could write the attachment in such a way that you can just add arbitrary objects, though you will have to manually supply types in that case (e.g. in a factory function), the usage would look something like: