首页 > 解决方案 > 参数类型不兼容 - 字符串和字符串数组

问题描述

我有一个接受onChange功能(属性)的组件。

其定义如下:

onChange: (str: string | string[]) => void;

因此,这意味着:str要么是stringOR 的数组,要么是string. 当我使用我的组件时,我有一个只接受单个字符串setNoOfCols的函数(是来自useStatehook -> 的函数):

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'.

如何为我的组件定义一个只使用单个字符串的函数?

标签: javascripttypescript

解决方案


您可以在使用时使用正确的签名来避免此错误,useState如下所示

const [noOfCols, setNoOfCols] = useState<string|string[]>('basic');

或者您可以onChange像这样更新您的类型定义:

type onChange = ((str: string|string[]) => void) | ((str: string[]) => void);

推荐阅读