箭头函数对象的打字稿接口

Typescrit interface for an object of arrow functions

我在尝试为以下结构定义接口时遇到问题:

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]:元素隐式具有'any'类型,因为字符串类型的表达式不能用于索引类型'Lookup'。在类型 'Lookup'.
  2. 上找不到参数类型为 'string' 的索引签名
  1. 在行 return fn({ ...params }) 中:需要 3 个参数,但得到 1 个

如有任何帮助,我将不胜感激。非常感谢:)

在你的情况下(来自沙箱):

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'
}