首页 > 解决方案 > 箭头函数对象的 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]内:元素隐式具有“任何”类型,因为字符串类型的表达式不能用于索引类型“查找”。在“查找”类型上找不到具有“字符串”类型参数的索引签名。
  1. return fn({ ...params })内:预期 3 个参数,但得到 1 个

我将不胜感激任何帮助。提前非常感谢:)

标签: javascripttypescriptjavascript-objectsarrow-functions

解决方案


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

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

推荐阅读