javascript - 箭头函数对象的 Typescrit 接口
问题描述
我在尝试为以下结构定义接口时遇到了问题:
interface JSONRecord {
[propName: string]: any;
}
type ReturnType = (id: string|number, field: string, record: JSONRecord) => string
export const formatDictionary = ({
mode = "render", key = "originalValue",
defaultKey = "originalValue"
}):ReturnType => (id, field, record) => {
...
}
interface Lookup {
Dictionary: ({mode, key, defaultKey}:{mode: string, key: string, defaultKey: string}) => ReturnType,
...
}
export const functionLookup:Lookup = {
Dictionary: formatDictionary,
...
}
export const formatField = (params:JSONRecord):string|ReturnType => {
const type:string = params.type
if (type === undefined) { return identity }
const fn = functionLookup[type]
if (fn === undefined) { return identity }
return fn({ ...params })
}
我收到以下错误:
- 行
const fn = functionLookup[type]
内:元素隐式具有“任何”类型,因为字符串类型的表达式不能用于索引类型“查找”。在“查找”类型上找不到具有“字符串”类型参数的索引签名。
- 我不太确定为什么会这样,我认为我在 Lookup 中定义的 Dictionary 应该被解释为字符串。当我将字典更改
[x: string]: ({mode, key, defaultKey}:{mode: string, key: string, defaultKey: string}) => ReturnType
为错误消失时,但我想具体说明可以传递的参数。
- 行
return fn({ ...params })
内:预期 3 个参数,但得到 1 个
- 我无法真正解决这个问题,该函数显然只需要 1 个对象作为参数
{mode, key, defaultKey}
,还是需要 ReturnType 函数?
我将不胜感激任何帮助。提前非常感谢:)
解决方案
在你的情况下(来自沙箱):
const anExampleVariable = "Hello World"
console.log(anExampleVariable)
// To learn more about the language, click above in "Examples" or "What's New".
// Otherwise, get started by removing these comments and the world is your playground.
interface Lookup {
test: number
}
const functionLookup:Lookup = {
test: 5
}
const params = {
type: 'test'
};
const type = params.type
const a = functionLookup[type]
params
变量被推断为{type: string}
。
在这里functionLookup[type]
,您想type
用作 的索引functionLookup
,但 TS 不能那样工作。因为您不能只使用通用类型string
作为类型的索引Lookup
。
Lookup
允许您仅使用文字test
作为索引。
所以你可以as const
为你的变量添加前缀params
。
const params = {
type: 'test'
} as const;
您可以使查找索引:
interface Lookup {
test: number,
[prop:string]:number
}
或者,您可以显式定义 Record 类型params
:
const params:Record<string, keyof Lookup> = {
type: 'test'
}
推荐阅读
- mysql - MySQL ON DUPLICATE KEY UPDATE 中的条件无法正常工作
- android - 如何在我的第一个应用程序中解决 onClickListener 错误
- java - 如何为同一个 CustomInfoWindow 设置不同的事件
- python - 脚本一直显示“SettingCopyWithWarning”
- javascript - 删除 div 内的“a”标签的“rel”属性
- docker - 如何将微服务架构中的不同容器与 api 网关连接起来?
- numpy - 在numpy中统一初始化二维数组
- php - Carbon 2 日期解析返回不同的结果
- javascript - 单击按钮时不断导航到我的 html 目录
- r - R - 如何在数据框中找到每行的三个最小值?