微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

箭头函数对象的 Typescrit 接口

如何解决箭头函数对象的 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 })
}

我收到以下错误

  1. 在行 const fn = functionLookup[type] 中:元素隐式具有“任何”类型,因为字符串类型的表达式不能用于索引类型“查找”。在“Lookup”类型上找不到参数类型为“string”的索引签名。
  • 我不确定为什么会发生这种情况,我认为我在 Lookup 中定义的字典应该被解释为字符串。当我将 Dictionary 更改为 [x: string]: ({mode,defaultKey: string}) => ReturnType 时,错误消失了,但我想具体说明可以传递的参数。
  1. return fn({ ...params }) 行中:需要 3 个参数,但得到 1 个
  • 我真的无法理解这一点,该函数显然只期望 1 个对象作为参数 {mode,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;

您可以将 Lookup 编入索引:

interface Lookup {
    test: number,[prop:string]:number
}

或者,您可以为 params 显式定义记录类型:


const params:Record<string,keyof Lookup> = {
    type: 'test'
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。