首页 > 解决方案 > 如何添加索引签名以导出默认对象

问题描述

第一.ts:

import textFilters from './second'
Object.keys(textFilters).forEach(key => {
  Vue.filter(key, textFilters[key])
})

第二个.ts:

export default {
  trimDescription: (text: string, length: number): string => {
    return text.length > length ? text.substring(0, length - 3) + '...' : text
  }
}

我收到关于缺少索引签名的错误。我怎么能把它添加到export default {}

更新 1

我可以在 second.ts 中这样做:

interface Keys {
  [key: string]: any
}

const obj: Keys = {
  trimDescription: (text: string, length: number): string => {
    return text.length > length ? text.substring(0, length - 3) + '...' : text
  }
}

export default obj

但最初的问题是,我可以这样做export default {}吗?

标签: typescript

解决方案


在对象中,像这样定义索引签名:

{
   [index: string]: any;

    ...rest of your object
}

将 any 替换为您希望对象值具有的实际类型。


推荐阅读