Using TypeScript with slot props: Best practices for managing types?

In my current project, I'm utilizing slot props. A key aspect is a generic component that accepts an Array as its input.

This is the structure of MyComponent:

<script lang="ts">
    export let data: Array<any>;
</script>

<div>
    <!-- some stuff ... -->
    {#each data as item}
        <slot {item} />
    {/each}
    <!-- ... and other stuff ... -->
</div>

When calling this component, it looks like this:

<script lang="ts">
    let myData : Array<MyType> = ...
</script>

<MyComponent data={myData} let:item>
    <li>{item.myVerySpecificField}
</MyComponent>

I'm struggling to figure out how to explicitly type the 'item' parameter as MyType. Do you have any insights on this?

Even though the current setup works fine, I'm missing compile-time checks for types.

Answer №1

Experimental implementation of generic components can be found here: https://github.com/dummdidumm/rfcs/blob/ts-typedefs-within-svelte-components/text/ts-typing-props-slots-events.md

To apply this in your scenario, consider the following:

MyComponent:

<script lang="ts">
  // define a generic
  type T = $$Generic;

  // use that generic
  export let data: Array<T>;
</script>

<div>
  <!-- some stuff ... -->
  {#each data as item}
    <slot {item} />
  {/each}
  <!-- ... and other stuff ... -->
</div>

Caller:

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

  type MyType = { field: "one" | "two" | "three" };

  let myData: Array<MyType> = [
    { field: "one" },
    { field: "two" },
    { field: "three" },
  ];
</script>

<MyComponent data={myData} let:item>
  <li>{item.field}</li>
</MyComponent>

item will have the appropriate typing in this setup.

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

Do we really need Renderer2 in Angular?

Angular utilizes the Renderer2 class to manipulate our view, acting as a protective shield between Angular and the DOM, making it possible for us to modify elements without directly interacting with the DOM ourselves. ElementRef provides another way to al ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

What is the method for opening the image gallery in a Progressive Web App (PWA)?

I am struggling to figure out how to access the image gallery from a Progressive Web App (PWA). The PWA allows me to take pictures and upload them on a desktop, but when it comes to a mobile device, I can only access the camera to take photos. I have tried ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

The young one emerges within the SecurePath component temporarily

Setting up authorization in React has been a priority for me. Ensuring that users cannot access unauthorized pages within the application is crucial. To achieve this, I have created a custom component as shown below. import { ReactNode } from "react&q ...

Choosing an element that does not have a particular string in its colon attribute name

In my code, I have multiple elements structured like this: <g transform="matrix"> <image xlink:href="data:image/png" width="48"> </g> <g transform="matrix"> <image xlink:href="specific" width="48"> </g> <g tran ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Tips for choosing a specific quantity and adjusting its value

Just starting out with Ionic 3 and looking for some help with the code. Can anyone assist me in understanding how to change the value of an item in a shopping cart and have the subtotal reflect that change? cart.ts private _values1 = [" 1 ", "2", " 3 "," ...

`Optimizing bundle size in Webpack using braintree-web integration with TypeScript`

When utilizing braintree-web 3.61.0 with Vue.js 2.6.11 and TypeScript 3.8.3, I organize the necessary components of braintree-web into a service in this manner: import { client, hostedFields, applePay } from 'braintree-web'; export default { cli ...

TypeScript's conditional property failing to recognize incorrect functional argument

The concept of a conditional type should encompass smart properties, and I sought assistance from @jcalz in the previous iteration of this query. Even though that issue was resolved, I am still unable to achieve the level of typing strictness I desire. The ...

Type guard does not narrow down the union type

Explore the following code snippet: type UnionType = 'foo' | 'bar' | 'baz' const obj = { foo: 'huh', bar: 'hmm' } function func(input: UnionType) { if(input in obj) { input } } In ...

Ways to pass styling properties to a nested component

I am working on a component that includes an input field: <mat-form-field appearance="standard"> <mat-label >{{label}}<span>*</span></mat-label> <input [type]="type" <span matSuffix>{{suffix} ...

Encountering the error message 'Object is of type unknown' when implementing the createAsyncThunk function post utilization of Typescript and Redux Toolkit

Currently, I am utilizing Typescript in my React application where Redux Toolkit is being used for state management. The data is being fetched from an Express Api and everything operates smoothly if Redux is implemented without Typescript. However, when in ...

Reacting to shared routes across various layouts

My React application has two layouts: GuestLayout and AuthLayout. Each layout includes a Navbar, Outlet, and Footer, depending on whether the user is logged in: AuthLayout.tsx interface Props { isAllowed: boolean redirectPath: string children: JSX.E ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Adding a Personal Signature to a PDF File Utilizing Form Elements in HTML, CSS, and JavaScript

After experimenting with jsPdf and signature pad, I found that adding a signature to a PDF created using forms was possible, but it was challenging to place the signature in the desired location. I am looking for a solution where if I input a PDF that alre ...

Deciding when to utilize an interface, when to avoid it, and when to opt for a constructor in Typescript for the creation of JavaScript arrays

Exploring the concept of JavaScript object arrays in TypeScript In my current project, I am retrieving a JSON array from an observable. It seems that I can define and initialize the array without necessarily specifying an interface or type. let cityList[ ...

Access the document within the Angular Material File Selection feature

I have implemented a Material file selection feature in my project. The code snippet below shows how I am doing it: <label for="uploadPicture" class="upload-file"> <mat-icon>add_a_photo</mat-icon> </label> <input type="file" ...

Learn the process of adjusting the Time Zone in Angular2-HighCharts!

I've been struggling for a few days now trying to adjust the UTC time in an area chart using Angular2-HighCharts. The backend API is returning timestamps which I then inject into the chart, but each time it's being converted to "human time" with ...