【问题标题】:This expression is not callable. Type 'string' has no call signatures此表达式不可调用。类型“字符串”没有调用签名
【发布时间】:2020-12-27 10:08:26
【问题描述】:

我正在尝试从一个对象创建一个模板文件,其中键可以是字符串或返回字符串的函数:

export const createDynamicTemplate = (
  templateParams: CreateDynamicTemplateParams
) => {
  const { template, projectPath = '', param = '' } = templateParams
  const updatedTemplateArr = Object.keys(template).map((key: string) => {
      return {
        [key]: {
          filePath: `${projectPath}/${key}`,
          template: typeof template[key] === 'function' ? 
          template[key](param) : template[key],
        },
      }
  })
  const updatedTemplate = Object.assign({}, ...updatedTemplateArr)
  return updatedTemplate
}

我的界面是:

export interface TemplateObject {
  [key: string]: string
}

export interface FunctionalTemplateObject {
  [key: string]: (param: string) => void
}

export interface CreateDynamicTemplateParams {
  template: FunctionalTemplateObject | TemplateObject
  projectPath: string
  param: string
}

它一直在createDynamicTemplate 中抛出此错误:

此表达式不可调用。 并非所有类型为 'string | ((param: string) => void)' 是可调用的。 类型“字符串”没有调用签名。

我在这里做错了什么?

【问题讨论】:

    标签: node.js typescript types


    【解决方案1】:

    检查引用对象的变量的子属性的类型不会缩小变量对象的类型。您可以先将键的值保存在单独的变量中,然后检查该值以缩小其类型:

    const updatedTemplateArr = Object.keys(template).map((key: string) => {
      const item = template[key];
      if (typeof item === 'function') {
        return {
          [key]: {
            filePath: `${projectPath}/${key}`,
            template: item(param),
          },
        }
      }
    })
    

    或者,更好的是,使用Object.entries 一次获取键和值。 (还要注意,不需要注意.map参数的类型——TS可以自动推断就可以了)

    const updatedTemplateArr = Object.entries(template).map(([key, value]) => {
      if (typeof value === 'function') {
        return {
          [key]: {
            filePath: `${projectPath}/${key}`,
            template: value(param),
          },
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 2020-07-10
      • 2020-09-09
      相关资源
      最近更新 更多