javascript - 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。
有人出主意吗?
解决方案
我无法使用以下代码在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);
}
}
让我知道以上是否解决了您的问题。
推荐阅读
- javascript - 从单独的 JS 文件访问数据响应项(控制台错误)
- javascript - CSS垂直对齐部分标签中的文本?
- javascript - 如何在 MySQL Nodejs 中建立一对多关系?
- javascript - JavaScript对象作为计数器不递增
- concurrency - 为什么要换!即使 Atom 的值没有改变,也要重试?
- excel - 如何将具有变量的另一个单元格的乘积放入一个单元格中?
- jquery - 当它们有多个时,我如何触发每个按钮?使用 jQuery
- html - 如何使用 Bootstrap 在 Jekyll 中包装文本而不是代码块?
- spring - Spring Security:认证后Referer始终登录页面
- redux - 使用中间件时属性“类型”的redux错误