I encountered an issue with Svelte (Vite) + Bootstrap 5 + SvelteStrap where it gave me the error message stating: "Cannot assign type 'string' to type 'ButtonColor'"

I am currently working with Svelte (Vite) + Bootstrap 5 + SvelteStrap. The code I have written is as follows:

<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bf9f4f4efe8efe9faebdbaeb5aab5ab">[email protected]</a>/dist/css/bootstrap.min.css">
</head>
<script>
    import { Button } from 'sveltestrap';
    let color = "danger";
</script>

<div>
    <Button color="{color}">{color}</Button>
</div>

While this code works fine in the browser, I am encountering an error in VSCode:

Type 'string' is not assignable to type 'ButtonColor'.

I am new to Svelte and I am attempting to modify the default example on the SvelteStrap website:

<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25474a4a51565157445565100b140b">[email protected]</a>/dist/css/bootstrap.min.css">
</head>
<script lang="ts">
  import { Button } from 'sveltestrap';
  const colors: any = [
    'primary',
    'secondary',
    'success',
    'danger',
    'warning',
    'info',
    'light',
    'dark'
  ];
</script>

{#each colors as color}
  <div>
    <Button {color}>{color}</Button>
  </div>
{/each}

When I use the default example, I do not encounter any errors. What could be the reason for this discrepancy? What am I missing?

Answer №1

This error arises from a typing issue in TypeScript.

The color property should have a union type of different string values, but when typed as an array of string literals by default, it becomes just string[], making its items no longer assignable to a specific string-literal-based type.

To solve this, you can use as const to enforce the array type to be literal-based:

const colors = [
    'primary',
    'secondary',
    'success',
    'danger',
    'warning',
    'info',
    'light',
    'dark'
] as const; // <--

Refer to the complete ButtonColor type definition here:

declare type ButtonColor =
  | 'primary'
  | 'secondary'
  | 'success'
  | 'danger'
  | 'warning'
  | 'info'
  | 'light'
  | 'dark'
  | 'link';

Although the type is not exported, you can extract it from the Button class like this:

import type { SvelteComponentTyped } from 'svelte';
import type { Button } from 'sveltestrap';

type PropsOf<C> = C extends SvelteComponentTyped<infer Props> ? Props : never;
type ButtonProps = PropsOf<Button>;
type ButtonColor = Exclude<ButtonProps['color'], undefined>;

For typing your array, you can also use this method:

const colors: ButtonColor[] = [
    'primary',
    'secondary',
    'success',
    'danger',
    'warning',
    'info',
    'light',
    'dark'
];

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

Unable to apply a dotted border to a horizontal rule when a Bootstrap 5 link is present

As I strive to add a dotted border-style to the horizontal rule on my website, an interesting challenge arises when the Bootstrap-5 CDN is included. The border-style does not take effect as expected. Even on Codeply, the border-style works perfectly until ...

How can I retrieve the date from the following week with Ionic?

I am looking to retrieve the date of today plus 7 days. Currently, I am retrieving today's date using the following code: public dateToday: string = new Date().toLocaleDateString('de-DE'); After searching on Google, I came across the soluti ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Typescript: Select just one option from the union

There is a specific Query type that contains the getBankAccounts property: export type Query = { getBankAccounts: GetBankAccountsResponseOrUserInputRequest, }; This property can return either a GetAccountsResponse or a UserInputRequest: export type Ge ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

What causes the vertical movement of my Bootstrap v5 card when resizing the window?

Issue: While working on my website and implementing three cards using Bootstrap, I encountered a problem. When I resize the window vertically, all the elements shift upwards and overlap with other elements, ruining the look of the site. I suspect the issu ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...

Ignore a directory during TypeScript compilation

When writing code in Atom, the use of tsconfig.json to include and exclude folders is essential. For optimal intellisense functionality, the node_modules folder must be included. However, when compiling to js, the node_modules should not be compiled. To ac ...

The parameter in Angular cannot be assigned a type of 'null'

@Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.curren ...

Prevent sidebar from adjusting size according to text length

Just started exploring Bootstrap 5 and noticed some significant differences from version 4. Check out this jsfiddle for a demonstration of my issue. The problem occurs when the lorem ipsum text exceeds a certain length, causing the sidebar width to be pu ...

Strategies for preventing multi-level inheritance of TypeScript class properties and methods

In my current JavaScript class structure, the DataService is defined as follows: // data.service.ts export class DataService { public url = environment.url; constructor( private uri: string, private httpClient: HttpClient, ) { } ...

The Angular 5 lifecycle hook ngOnChanges is triggered just once in a child component

I am struggling with syncing a child component containing complex input (such as chart data) with the API response received in the parent component in Angular 5. I am using the @Input() decorator to pass the chart data from the parent to the child componen ...

Navigating the parent scope in Angular using TypeScript

Is there a way to access the parent Controller's scope from within the TypeScript class? Here is the code snippet: export class EntityOverviewCtrl extends AbstractCtrl { public static $inject = ["$state", "$http", "CurrentSession"]; publi ...

Encountering: Unable to break down the property 'DynamicServerError' of 'serverHooks' as it does not have a defined value

An error has arisen in a Nextjs app with TypeScript, specifically in the line of my react component which can be found here. This is my inaugural package creation and after several trials, I managed to test it successfully in a similar vite and TypeScript ...

Encountering an issue with creating an App Runner on AWS CDK

Attempting to deploy my application using App Runner within AWS via CDK. Utilizing the reference from https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apprunner.Service.html. Upon deployment, encountering the following error: create_failed: R ...

Tips for calculating the total of keyup elements in an Angular application

There are "N" inputs in a formgroup that need to be summed: <input (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao"> This is the Typescript code: sum( ...

Typescript encounters a failure in typing when an object is destructured

There is a function that returns an object with two properties (res, mes) where one of them could be null: const fetchJSON = <Res, Body>(link: string, body: Body): Promise<{ res: Res; mes: null } | { res: null; mes: Popup }> => { return n ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

Tips for creating a Single Xpath instead of Multiple paths

I'm currently working with Protractor alongside TypeScript. I have an element located at: xpath = "**//div[@class='loglist']/div[1]/div[2]**" Afterwards, there are additional elements that need to be identified in different divs s ...