1

I've got a simple react component where I have input which should be able to become one of to types. I don't know how to do this, if it's possible. If not what would be a good practices of archiving the same effect?

import * as React from 'react'

interface Checkboxes {
  label?: string
  items: any //should be either string[] or CheckboxItem[]
}

interface CheckboxItem {
  text: string
  checked?: boolean
}

export default function Checkboxes(props: Checkboxes) {
  const {
    label,
    items,
  } = props

  return (
    <fieldset className="checkboxes">
      {label && <legend>{label}</legend>}
      {items.map((item, index) => <label key={index}><input type="checkbox" defaultChecked={item.checked} />{item.text}</label>)}
    </fieldset>
  )
}

` As i tried union types the following error appears on the map function:

(property) Array<T>.map: (<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: CheckboxItem, index: number, array: CheckboxItem[]) => U, thisArg?: any) => U[])
Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param callbackfn — A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param thisArg — An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

This expression is not callable.
  Each member of the union type '(<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: CheckboxItem, index: number, array: CheckboxItem[]) => U, thisArg?: any) => U[])' has signatures, but none of those signatures are compatible with each other.ts(2349)

Kind regards

1 Answer 1

4

items: any //should be either string[] or CheckboxItem[]

Using a union type.

Example

interface Checkboxes {
  label?: string
  items: string[] | CheckboxItem[]
}
Sign up to request clarification or add additional context in comments.

7 Comments

I tried this, however I get an error message in the items.map() function.
@pgalle is it possible the error message isn't complaining about the Array type? Think about .map(item => {}), what type is item?
@stealththeninja item is of type string I'd say.
@pgalle does the compiler know that? ;) My Typescript is rusty but I think you can cast it: .map(<string>item => {}). Type any is permissive which is why I'm guessing you didn't see an error before.
@stealththeninja if I cast item to type string, then the component wont work when using my custom type CheckboxItem
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.