首页 > 解决方案 > TypeScript - 实用方法中的错误

问题描述

我有以下实用方法。它有两个参数,inputValueselectOptions

export interface SelectType {
  label: string;
  value: string;
}

const checkCaseSensitiveSelectUtil = (inputValue: SelectType, selectOptions: SelectType[]): any => {
  const exactValueExists = selectOptions.find(input => input.value === inputValue);
  const valueIsNotEmpty = inputValue.trim().length;

  return !exactValueExists && valueIsNotEmpty;
};

export default checkCaseSensitiveSelectUtil;

但我收到以下错误: 1.input.value === inputValue我收到以下信息:

(parameter) input: SelectType
This condition will always return 'false' since the types 'string' and 'SelectType' have no overlap.ts(2367)
  1. trim我得到这个:
Property 'trim' does not exist on type 'SelectType'.ts(2339)

任何人都知道如何真正消除这两个错误。我的意思是,由于参数是那种确切的类型,我唯一的选择是将它们都转换为任何参数吗?

标签: javascriptreactjstypescriptinterface

解决方案


1.

您正在比较input.value(字符串类型)和inputValue(类型SelectType)。一种可能的解决方案是将 的值input与 的值进行比较inputValue

selectOptions.find(input => input.value === inputValue.value);

2.

const valueIsNotEmpty = inputValue.trim().length;

因为inputValue不是价值,而是SelectType你的一个实例,不能只是修剪它。

尝试获取值(字符串)

const valueIsNotEmpty = inputValue.value.trim().length;

您应该考虑重命名变量。命名有点令人困惑;)


推荐阅读