1

第一.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 {}吗?

4

2 回答 2

0

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

{
   [index: string]: any;

    ...rest of your object
}

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

于 2019-10-06T12:55:49.453 回答
0

我实际上已经解决了这个问题:

main.ts:

import textFilters, { Keys } from '@/filters/text'
(Object.keys(textFilters) as Array<(keyof Keys)>).forEach(key => {
  Vue.filter(key, textFilters[key])
})

文本.ts:

export interface Keys {
  trimDescription(text: string, length: number): string
}

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

关键是:Object.keys(textFilters) as Array<(keyof Keys)>

于 2019-10-19T05:28:54.240 回答