【问题标题】:Adding properties to an existing type with TypeScript使用 TypeScript 向现有类型添加属性
【发布时间】:2017-06-15 10:06:59
【问题描述】:

所以我有一个用 TypeScript 编写的库,它使用 NPM 依赖 'ldapjs'。

我的项目中也安装了@types/ldapjs

所以在我的项目中,我有这个:

import {Client} from '@types/ldapjs';
import * as ldap from 'ldapjs';

现在这是我的问题 - 如何将属性添加到类型为 Client 的客户端?

我有这个:

export interface IClient extends Client{
  __inactiveTimeout: Timer,
  returnToPool: Function,
  ldapPoolRemoved?: boolean
}

其中 IClient 是我的 ldapjs 客户端版本,带有一些额外的属性。

let client = ldap.createClient(this.connOpts);  // => Client
client.cdtClientId = this.clientId++;

但问题是,如果我尝试向客户端添加属性,我会收到此错误:

'cdtClientId' 属性在客户端类型上不存在。

有什么方法可以将 Client 转换为 IClient?

我该怎么做?我在许多不同的项目中都有同样的问题。

【问题讨论】:

    标签: node.js typescript typescript2.0


    【解决方案1】:

    虽然您添加的答案可能会解决您的问题,但您可以直接扩充Client 接口并添加属性。你甚至不需要IClient。你可以使用module augmentation:

    declare module "ldapjs" {
        interface Client {
            // Your additional properties here
        }
    }
    

    【讨论】:

      【解决方案2】:

      哇,这并不难,几个月来我一直在想如何做到这一点。

       let client = ldap.createClient(this.connOpts) as IClient;
      

      我们使用as 表示法将泛型类型转换为更具体的类型(我认为这是正确的表达方式)。

      我通过这篇文章解决了这个问题: http://acdcjunior.github.io/typescript-cast-object-to-other-type-or-instanceof.html

      【讨论】:

        猜你喜欢
        • 2020-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 2022-08-18
        • 2016-09-22
        • 2021-05-02
        • 2017-02-26
        相关资源
        最近更新 更多