Utilizing Svelte Components within Object Properties

I am trying to pass a component as a prop.

import AComponent from './AComponent.svelte';

type MyType = {
  [key: string]: any; // just an example
}

type AcceptComponentProp<T> = {
  component: SvelteComponentTyped<{ record: T }>;
}

const componentPropObject: AcceptComponentProp<MyType> = {
  component: AComponent // getting an error here
}
Error: Type 'typeof AComponent__SvelteComponent_' is missing the following properties from type 
'SvelteComponentTyped<{ record: MyType; }>': $set, $on, $destroy, $$prop_def, and 5 
more.ts(2740)

I thought changing the typedef might help:

type AcceptComponentProp<T> = {
  component: typeof SvelteComponentTyped<{ record: T }>;
}

But that led to even more strange errors.

It's crucial for this typing to be clear and explicit since it will be part of the interface exposed to users.

Answer №1

To properly type IWantToAcceptAComponent, you cannot directly use SvelteComponentTyped as it refers to the instance type, not the constructor type. Attempting to do

typeof SvelteComponentType<..some generic>
will result in a TypeScript syntax error. Instead, utilize Svelte's provided ComponentType interface to define a class constructor that returns a specific instance like this:

import type { ComponentType, SvelteComponentTyped } from 'svelte';

type IWantToAcceptAComponent<T> = {
  component: ComponentType<SvelteComponentTyped<{ record: T }>>;
  // For older Svelte versions lacking ComponentType:
  componentAlternative: new (...args: any) => SvelteComponentTyped<{ record: T }>;
}

Ensure you have Svelte for VS Code version 105 or higher and (if applicable) svelte-check 2.0.0 or newer installed for these typings to function correctly. Previous version mismatches may cause issues.

If utilizing this code in a TypeScript file, activate the TypeScript plugin within the Svelte for VS Code extension to avoid generic typing of all Svelte imports as SvelteComponentDev.

Answer №2

Although I am not experienced in using typescript, I don't see any reasons why achieving this functionality would be possible with vanilla JavaScript but not with TS. I have created a REPL that essentially wraps two 'sub components' passed as props.

The structure looks like this:

App.svelte

<script>
  //App.svelte
  import A from "./A.svelte";
  import B from "./B.svelte";
  import Wrapper from "./Wrapper.svelte";

  let props = [  { component: A }, { component: B } ];
</script>

<Wrapper {props} />

Wrapper.svelte :

<script>
    //Wrapper.svelte
    export let props = [];
</script>

{#each props as prop}
    <p>
        <svelte:component this={prop.component} />
    </p>
{/each}

A.svelte :

   <!-- A.svelte -->
   <h2>COMP A</h2>

B.svelte :

    <!-- B.svelte -->    
    <h3>COMP B</h3>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Socket.io: The other client will only update when there is interaction happening

I am currently facing a challenge setting up a real-time application using socket.io in Angular and node.js. The application is not functioning as expected. When a client makes a new post, the other clients do not receive updates until there is some inter ...

Uncovering the Mutable Object Type within an Immutable Object

I would like to create a type that specifically extracts the mutable object type from an existing immutable object type like such: import * as Immutable from 'seamless-immutable' interface IObjType { field: string; } type TObjImmType = Immuta ...

The absence of the @Injectable annotation is causing an issue when importing a JSON

I am currently in the process of integrating a JSON file into my service by using a @inject() tag within the constructor. Below is the code snippet I am working with. DependencyInjectionContainer.ts import { Container, decorate, injectable } from "invers ...

Angular's OnChanges event is triggering for an Input variable, however the variable remains unchanged

I've encountered a new issue that I'm hoping someone can help me with. I'm working on a simple parent-child component relationship where an Input variable is passed into a ChildComponent. The ChildComponent in question is a bootstrap modal, ...

Modifying a property in a nested layout through a page in Next.js 13

Currently, I am facing a challenge in updating the page title within a nested layout structure. app/docs/layout.tsx: export const DocsLayout = ({children}:{children: React.ReactNode}) => { return ( <> <header> ...

Error 2300 in Vetur: Identical identifier found for '(Missing)'

Recently, I've been encountering a strange issue with Vetur in my typescript nuxt.js project. Every component, whether it's just an empty line or contains code, displays an error message on the first line. I can't pinpoint when this problem ...

How come this mocha test is exceeding its timeout limit when making a basic call with mongoose?

Trying to write a simple assertion for an asynchronous database method: describe('User Repository', () => { describe('findById', () => { it('Returns a user that can be found in the database by ID', async () => { ...

Ensure the type of a variable matches another variable

Can another variable function as a type guard? Consider the following code snippet: let foo: string | null = Math.random() > .5 ? null : 'bar' const otherProp = true const test = foo !== null && otherProp function foobar(x: string){} ...

Issue with updating values in a ReactJS function

My ReactJs function is designed to display a simple dialogue box and update a value for the parent component. Here is an example of how the function is structured: export function MyDialogue(props: IMyProps) { var myValue = 0; return ( ...

Saving data from a one-to-one relationship using TypeORM and NestJS in a socalled way is a breeze - here's how you

When working with TYPEORM, I have a requirement to create two entities in the database: one for the user and another to store tokens. However, I face a challenge when trying to fill both entities simultaneously during the user creation process. Can someone ...

Leveraging environment variables in template documents

Can you incorporate environment variables into template files successfully? Currently, I am experimenting with the following syntax: <img class="preview-image" src="{{environment.assets + item.image}}" /> However, this approach leads to the follow ...

The parameter type '{ email: string; }' in NGXS does not accept arguments of type 'string'

Struggling to retrieve data from an API using ngxs with this.store.dispatch(new GetUser(userEmail)) Attempted to use the user id stored in local storage as a string and convert it to a number but encountered a similar error (Argument of type 'string&a ...

Tips for displaying text on the bubbles of a vector map using the DevExpress library in an Angular and TypeScript environment to showcase counts or other relevant information

I managed to incorporate the devextreme angular 2 map into my demo project. My goal is to display the count of individuals with the name 'x' on the bubble as a label/text on the vector map, without the need for hovering to see a tooltip. I want t ...

Angular 6: The Promise<any> is incompatible with the LeagueTable type

Recently delving into Angular and attempting to retrieve JSON League Table data from the API, I encountered an error message stating Type 'Promise' is not assignable to type 'LeagueTable'. leaguetable.service.ts import { Injectable } ...

How does Zone.js enhance the functionality of Angular 2?

I am currently delving into the world of Angular 2.0 and stumbled upon the mysterious file known as Zone.js. I am curious to understand the role of Zone.js and how it can enhance the performance of my application. ...

Having trouble with react-i18next not working properly in my React Native application

I recently initiated a new react-native project, but I seem to be encountering an issue with my react-i18next translations. Despite having the keys correctly set up, I am unable to view the translations. Furthermore, I have noticed that my components are ...

A call signature is missing in the expression type of Typescript, preventing it from being invoked

While I know there are similar questions out there, none of them have provided the answer I'm looking for. My goal is to create a straightforward function in my Angular application. In my app.component.ts file: formClick() { const formContainer ...

How to change a specific value in an array of objects using React

Within my array, I have objects containing the fields id and title const cols = [ { id: 0, title: "TODO" }, { id: 1, title: "InProgress" }, { id: 2, title: "Testing" }, { ...

The properties required for type 'never[]' are not present

The type 'never[]' does not have the necessary properties from type '{ login: string; id: number; node_id: string; avatar_url: string; url: string; }': login, id, node_id, avatar_url, url When working on a component that takes an ApiUr ...

Scroll automatically to the last div whenever a button is clicked using React and Typescript

I'm currently working on an application being developed in React + Typescript. I am trying to implement auto-scroll functionality to the last div within a parent div where child divs are dynamically added based on data from an array of objects. The da ...