Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt:

Presentation.svelte

<script lang="ts">
    export let slides;
</script>

{#each slides as slide}
    <svelte:component this={slide.component} {...slide} />
{/each}

+page.svelte

<script lang="ts">
    import TitleSlide from '$lib/components/Slides/TitleSlide.svelte';
    import Presentation from '$lib/components/Presentation.svelte';
    import HeaderSlide from '$lib/components/Slides/HeaderSlide.svelte';

    const slides = [
        {
            component: TitleSlide,
            //
        },
        {
            component: HeaderSlide,
        }
    ]
</script>

<Presentation {slides} />

TitleSlide.svelte

<script lang="ts">
    import BaseSlide from './BaseSlide.svelte';

    export let title: string;
    export let subtitle: string;
</script>

<BaseSlide>
    <div class="flex flex-col items-center">
        <h1 class="text-8xl font-bold">{title}</h1>
        <h2 class="text-4xl">{subtitle}</h2>
    </div>
</BaseSlide>

HeaderSlide.svelte

<script lang="ts">
    import BaseSlide from './BaseSlide.svelte';

    export let header: string;
</script>

<BaseSlide>
    <h3 class="text-6xl">{header}</h3>
</BaseSlide>

BaseSlide.svelte

<section class="flex h-screen items-center justify-center bg-slate-300">
    <slot />
</section>

I am seeking a solution to define all the slides in the slides array within +page.svelte, using props based on the component's type in Typescript. After some research, I discovered that components can be typed using

writable<typeof SvelteComponent>
as mentioned in this StackOverflow post. However, when attempting to use it like
export let slides: writable<typeof SvelteComponent>[];
, I encountered an error. I also tried
export let slides: Writable<typeof SvelteComponent>[];
, but faced an issue with the import statement. Any suggestions on resolving this?

Answer №1

writable generates a store, which is not directly related to components themselves. The writable store is typically of type Writable<T>.

A component should simply be typed as ComponentType. The slides would then have the following typing:

export let slides: { component: ComponentType }[]

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

While working on a project in React, I successfully implemented an async function to fetch data from an API. However, upon returning the data, I encountered an issue where it was displaying as a

I am working with React and TypeScript and have the following code snippet: const fetchData = async () => { const res: any = await fetch("https://api.spotify.com/v1/search?q=thoughtsofadyingatheist&type=track&limit=30", { met ...

Using Jest in Typescript to simulate fetch responses

I am currently facing an issue with mocking the global fetch function using Jest and dealing with the Response type. Specifically, I only require the response.ok and response.json properties, but I am struggling to set the return data of fetch without spec ...

Click on the button to generate a PDF report using Internet Explorer 11

After encountering some challenges with printing a PDF report specifically on IE 11, I am reaching out for help. The code snippet below works perfectly in Chrome, but when it comes to IE 11, everything falls apart. Just to provide some context, I am develo ...

Activate the child for an update

Welcome! I am a newcomer to Angular and would greatly appreciate any assistance. The parent component of my picker has the ability to create various rules for each option. However, these rules are dynamic and can change frequently. I need to ensure that ...

Send the function to the directive

Below is the code for a directive: module app.directives { interface IDmDeleteIconController { doAction(): void; } class DmDeleteIconController implements IDmDeleteIconController { static $inject = ['$scope']; ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

Converting CommonJS default exports into named exports / Unable to load ES module

I've encountered an issue while creating a Discord bot with discord.js using TypeScript. When attempting to run the resulting JavaScript code, I'm facing an error that states: import { Client, FriendlyError, SQLiteProvider } from 'discord.js ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

reconfigure components by resetting settings on a different component

In the interface, I have a section that displays text along with a unique component titled FilterCriteriaList. This component includes custom buttons that alter their color when clicked. My goal is to reset the settings in the FilterCriteriaList component ...

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

What are the best practices for integrating Qt with React in TSX?

While I've figured out how to communicate qt with JS successfully, the challenge arises when trying to use React in TSX for frontend development. The previous solution failed on this front. Backend code: #./main.py import os from PySide6.QtWidgets ...

Typescript's confidential variables

Currently, I am delving into the world of Angular2 and familiarizing myself with working with classes in javascript for the first time. I'm curious about the significance of using the private parameter in the constructor, as opposed to simply writing ...

What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable. Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escaped ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...

Tips for showcasing an array containing two different types of objects in Angular

After sending a request to a remote server, I am returned with a JSON array. However, the array can contain two different types of JSON objects: [ { "country": "USA", "caseCount": 561, "caseDates": [], ...

Setting up the 'nativescript-stripe' plugin in your NativeScript Vue project for seamless integration

Trying to integrate the «nativescript-stripe» plugin into my Nativescript Vue app has been a challenge. The documentation and demos on the plugin's GitHub are geared towards Angular and TypeScript, making it difficult to adapt for Vue. Can anyone pr ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

The value of an Angular rxjs BehaviorSubject can be updated using the value property directly, without calling

While testing my code, I stumbled upon unexpected mutation. Perhaps I am doing something wrong. User constructor( public id: number, public education: Education[] ){} UserStateService private user = a new BehaviorSubject<User>(null); setUser(us ...