thecodejack
thecodejack

Reputation: 13379

How to verify if prop passed is a Component type in Svelte?

I am having a prop which takes either a function or Component. So I want to differentiate by checking types of prop whether it's a component or function. I am at present using following one. This may not work in prod when code gets obfuscated. Wanted to know better solution?

let isSvelteComponent = component => {
    return (
      typeof component !== "undefined" &&
      component.__proto__.name === "SvelteComponentDev"
    );
  };

Upvotes: 6

Views: 2286

Answers (2)

rixo
rixo

Reputation: 25001

I would argue that, loosely speaking, any function can potentially be a valid Svelte component:

<script>
    import B from './B.svelte'

    const C = function(opts) {
        return new B(opts)
    }
</script>

<B />   

<C />

REPL

As such, there isn't really a completely reliable way to tell appart a Svelte component from a regular function.

In your case, if the Svelte component and the function have different meaning and should be handled differently, maybe they should be passed through different props? That would allow to know for sure what is what, and what it is intended for.

Upvotes: 3

thecodejack
thecodejack

Reputation: 13379

I was able to fix this by checking prototype like following

import { SvelteComponent } from "svelte";
let isSvelteComponent = component => {
   return SvelteComponent.isPrototypeOf(component);
};

Upvotes: 1

Related Questions