1

目标是在我的 TypeScript 代码中进行代码拆分。

我使用(实验性)装饰器来支持从模型到持久存储的类似 ORM 的数据映射。其中一种类型需要使用表名参数化装饰器,该表将存储该类型的实体。为了进行代码拆分,我已将域模型提取到单独的文件 ( entity-model.ts) 中:

/* I am using dynamodb-data-mapper */
import { 
  table,
  hashKey,
  attribute
} from '@aws/dynamodb-data-mapper-annotations'

export class Entity {
  /* attributes */
}

/* this entity is parameterized with name of the table
   where data will be stored */
export function entityGroupClassFactory(tableName: string)/*: ???*/ {
  @table(tableName)
  class EntityGroup {
    @hashKey()
    id: string,

    @attribute({ memberType: embed(Entity) })
    children: Entity[]

  }
  return Entity
}

当我以下列方式使用此文件时:

import { entityGroupClassFactory, Entity } from './entity-model.ts'
import { DataMapper } from '@aws/dynamodb-data-mapper';

const mapper : DataMapper = createDataMapper()
const tableName : string = deterineTableName()

const EntityGroup = entityGroupClassFactory(tableName)

/* eventually I do */

let entityGroup = mapper.get(/*...*/)

/* and at some point I am trying to do this: */

function handleEntityGroup(entityGroup: EntityGroup) {
  /* ... */
}

/* or this: */

async function fetchEntityGroup(): Promise<EntityGroup> {
  const entityGroup = /* ... */
  return entityGroup
}

对于这两个函数 (handleEntityGroupfetchEntityGroup),TypeScript 报告以下错误:

[ts] Cannot find name 'EntityGroup'. [2304]

我不确定这种方法的正确性,我会寻找其他选项来进行代码拆分。但是作为该领域的初学者,我想回答以下问题:此示例代码中有什么?EntityGroup

谢谢你。

4

1 回答 1

1

当你声明一个类时,你会得到一个带有类名的值(表示类构造函数)和一个类型(表示类的实例类型)。

当您使用函数返回一个类并将其放入时,const您基本上只是获取值,没有理由创建实例类型。

幸运的是,您可以使用InstanceType<typeof EntityGroup>构造函数来获取实例类型EntityGroup

const EntityGroup = entityGroupClassFactory(tableName)
type EntityGroup = InstanceType<typeof EntityGroup>
于 2019-01-24T18:13:31.947 回答