【问题标题】:TypeScript - Errors in a Utility MethodTypeScript - 实用方法中的错误
【发布时间】:2019-11-28 06:56:09
【问题描述】:

我有以下实用方法。这需要两个参数,inputValue 和 selectOptions。

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)

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

【问题讨论】:

  • 你的参数 inputValue 不是字符串而是对象! inputValue: SelectType...你可能需要比较这个对象的属性... nput.value === inputValue.label (or inputValue.value)
  • 对不起。我不懂你在说什么。你能提供更多关于这个问题的信息吗?也许是一个例子?抱歉给您添麻烦

标签: javascript reactjs typescript interface


【解决方案1】:

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;

您应该考虑重命名变量。命名有点混乱;)

【讨论】:

    猜你喜欢
    • 2022-08-09
    • 2022-09-28
    • 2017-08-18
    • 2017-01-23
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2021-10-01
    • 2014-10-10
    相关资源
    最近更新 更多