javascript - 参数类型不兼容 - 字符串和字符串数组
问题描述
我有一个接受onChange
功能(属性)的组件。
其定义如下:
onChange: (str: string | string[]) => void;
因此,这意味着:str
要么是string
OR 的数组,要么是string
. 当我使用我的组件时,我有一个只接受单个字符串setNoOfCols
的函数(是来自useState
hook -> 的函数):
const [noOfCols, setNoOfCols] = useState<string>('basic');
...
onChange: (value: string): void => setNoOfCols(value)
不幸的是,我从 Typescript 收到一条错误消息,说
TS2322: Type '(value: string) => void' is not assignable to type '(str: string | string[]) => void'.
Types of parameters 'value' and 'str' are incompatible.
Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.
如何为我的组件定义一个只使用单个字符串的函数?
解决方案
您可以在使用时使用正确的签名来避免此错误,useState
如下所示
const [noOfCols, setNoOfCols] = useState<string|string[]>('basic');
或者您可以onChange
像这样更新您的类型定义:
type onChange = ((str: string|string[]) => void) | ((str: string[]) => void);
推荐阅读
- javascript - 如何用jquery扩展表行?
- javascript - 在单独的组件中访问变量的状态
- javascript - React Native,在导航中将两个值传递到下一个屏幕
- module - Veins 文档模块
- node.js - 使用 Node Build 'ng build' 耗尽内存 - Angular App
- arrays - 在 C++ 中使用变量声明结构数组
- ios - SwiftUI:从嵌套视图调用方法
- python - 试图在 DataFrame 中的切片副本上设置一个值。尝试改用 .loc[row_indexer,col_indexer] = value
- python - 如果可能,合并,否则 concat pandas
- python - matplotlibrc 中 figure.patch.set_facecolor(somecolor) 的设置