【问题标题】:What type has the `class` created by a `function`?`function`创建的`class`是什么类型的?
【发布时间】:2019-01-24 18:00:58
【问题描述】:

目标是在我的 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 是什么?

谢谢。

【问题讨论】:

    标签: typescript decorator code-splitting first-class


    【解决方案1】:

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

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

    幸运的是,您可以使用InstanceType&lt;typeof EntityGroup&gt; 来获取与构造函数EntityGroup 关联的实例类型。

    const EntityGroup = entityGroupClassFactory(tableName)
    type EntityGroup = InstanceType<typeof EntityGroup>
    

    【讨论】:

    • 哦,谢谢你这么快的回答!我现在只是想了解,是否可以将这两个东西(构造函数和实例类型)合并在一起。我将通读高级类型文档,非常感谢您指出 TS 的此功能。
    • 我一定会的!但我想更好地理解答案。我可以请您澄清“const”部分。如果我把它放入变量而不是常量,会有什么不同吗?
    • @Alexander 不,没关系。也许这将有助于理解值 VS 类型stackoverflow.com/questions/51131898/…
    猜你喜欢
    • 2021-09-24
    • 2010-09-26
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2021-07-31
    • 2011-04-29
    相关资源
    最近更新 更多