首页 > 解决方案 > Typescript 在接口中定义字符串类型的属性 | () => 字符串给出“无法调用表达式错误”

问题描述

我已经定义了一个像这里描述的接口定义 TypeScript 变量类型函数或字符串

它看起来像这样:

type displayWithFn<T> = (value: T) => string;
export interface Value<T> {
  value: T,
  displayValue: string | displayWithFn<T>;
}

在我的代码中,我有一个函数

getDisplayValue(item: Value<T>): string {
    
    if (typeof item.displayValue === 'string') {
      return item.displayValue  as string;
    } else {
      return item.displayValue(item.value);
    }
  }

第二行item.displayValue(item.value)确实给了我错误“TS2349 无法调用类型缺少调用签名的表达式。类型字符串 | displayWithFn 没有兼容的调用签名。”

我的 TypeScript 版本是 3.5.3。

有人出主意吗?

标签: javascripttypescript

解决方案


我无法使用以下代码在TypeScript 游乐场中重现该问题:

type displayWithFn<T> = (value: T) => string;

export interface Value<T> {
  value: T,
  displayValue: string | displayWithFn<T>;
}

function getDisplayValue<T>(item: Value<T>): string {
    if (typeof item.displayValue === 'string') {
        return item.displayValue  as string;
    } else {
        return item.displayValue(item.value);
    }
}

让我知道以上是否解决了您的问题。


推荐阅读