G-key
G-key

Reputation: 83

How to resolve Typescript Error of Property that does not exist on type of a slotted component using Carbon Component Svelte

The ComboBox from carbon-components-svelte accepts a slotted component to be used to render the each option.

https://svelte.carbondesignsystem.com/components/ComboBox#custom-slot

The type for each option of the ComboBoxItem is this.

export interface ComboBoxItem {
  id: ComboBoxItemId;
  text: string;
  disabled?: boolean;
}

Using the actual data, Typescript errors out because the data item's signature does not match.

How can I reconcile the following errors below, since the associated type is defined in the package, carbon-component-svelte? Thanks for all pointers.

Property 'description' does not exist on type 'ComboBoxItem' .. etc.

enter image description here

Some relevant code for response handles.

<script>
import type { ComboBoxItem } from 'carbon-components-svelte/types/ComboBox/ComboBox.svelte';

function itemToString(item: CamsComboBoxItem): string {
    return item.name || '';
}

    
interface CamsComboBoxItem extends ComboBoxItem {
    id: number;
    name?: string;
    description?: string;
    versionNumber?: string;
}

const items: CamsComboBoxItem[] = Array.from(Array(3)).map((e, i) => ({
    ...mockdata,
    name: `Variant Name ${i}: ${mockdata.name}`,
    // text: `Variant Name ${i}: ${mockdata.name}`,
    description: `Variant Description ${i}: ${mockdata.description}`,
    versionNumber: mockdata.versionNumber + '.' + i,
    id: i,
}));


</script>

<ComboBox
    titleText="Contact"
    placeholder="Select contact method"
    let:item
    let:index
    items={items}
    selectedId={1}
    {itemToString}
>
    <div title={item.description}>
        <strong>{item.name}</strong>
    </div>
    <div>
        Version Number: {item.versionNumber}
    </div>
    <div>
        index: {item.id}
    </div>
</ComboBox>

Upvotes: 0

Views: 27

Answers (1)

G-key
G-key

Reputation: 83

One of ChatGPTs answer.

To handle custom properties like description and versionNumber, you can cast item to your CamsComboBoxItem type:

<ComboBox
    titleText="Contact"
    placeholder="Select contact method"
    let:item
    let:index
    items={items}
    selectedId={1}
    {itemToString}
>
    <div title={(item as CamsComboBoxItem).description}>
        <strong>{(item as CamsComboBoxItem).name}</strong>
    </div>
    <div>
        Version Number: {(item as CamsComboBoxItem).versionNumber}
    </div>
    <div>
        index: {item.id}
    </div>
</ComboBox>

This approach explicitly informs TypeScript that item can have additional properties like description and versionNumber. Type assertions (as CamsComboBoxItem) ensure compatibility without changing the underlying ComboBoxItem type definition.

Upvotes: 0

Related Questions