簡體   English   中英

如何在 TypeScript 中分配多種可能的類型

[英]How to assign multiple possible types in TypeScript

我有一個簡單的反應組件,我有輸入應該能夠成為類型之一。 如果可能的話,我不知道該怎么做。 如果不是,那么存檔相同效果的良好做法是什么?

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>
  )
}

` 當我嘗試聯合類型時,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)

親切的問候

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

使用聯合類型。

例子

interface Checkboxes {
  label?: string
  items: string[] | CheckboxItem[]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM