Home > Mobile >  semantic ui typescript correct return type function for dropdown options
semantic ui typescript correct return type function for dropdown options

Time:10-06

After sifting through the internet I came to the conclusion I should just ask.

I have a Semantic-UI form in React with TypeScript (strict).

I'm trying to provide options from my rest api to a dropdown (select) in the form (trimmed unnecessary code):

Form[.tsx]:

<Form.Select options={()=>{getOptions()}} />

And my getOptions function:

//I put the DropdownItemProps[] type because I thought it would solve my issue
const getOptions = ():DropdownItemProps[] => {
    let options = new Array<DropdownItemProps>();
    //... restful request
    return (options)
}

TypeScript screams at me:

Type '() => void' is missing the following properties from type 'DropdownItemProps[]': pop, push, concat, join, and 27 more.ts(2740).
FormSelect.d.ts(24, 3): The expected type comes from property 'options' which is declared here on type 'IntrinsicAttributes & FormSelectProps & { children?: ReactNode; }'

I'm not sure why ts detects my function as '()=>void' (when I hover the function it clearly detects it as () => DropdownItemProps[]). To be honest I'm not even sure DropdownItemProps[] is the correct type I need to return from my getOptions() function.

Edit: just to be clear, if I change the call to options={()=>getOptions()}, options={getOptions} or anything similar, I get the same result but instead of '()=>void' it admits the the return value is '()=>DropdownItemProps[]'.

I basically looked everywhere I could think of, but Semantic-UI's docs don't have anything on TypeScript (which is kinda annoying).

Any help would be appreciated.

CodePudding user response:

here is a working example seems your getOptions function is not returning an array of objects

import React, { FC } from "react";
import { Form } from "semantic-ui-react";

const getOptions = ():DropdownItemProps[]=> {return [{'keyA': 'label A'}, {'keyB': 'label B'}]}


const Test=()=>{
    
    return (

        <Form>
            <Form.Select options={getOptions()} />
            </Form>

    )
}

export {Test}
  • Related