Alexander Mills
Alexander Mills

Reputation: 100010

Adding properties to an existing type with TypeScript

So I have a library written in TypeScript, which uses the NPM depenedency 'ldapjs'.

I also have @types/ldapjs installed into my project.

So in my project, I have this:

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

Now here is my question - how can I add properties to a client with type Client?

I have this:

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

where IClient is my version of an ldapjs Client with a few extra properties.

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

but the problem is, if I try to add properties to client, I get this error:

'cdtClientId' property does not exist on type Client.

Is there some way I can cast Client to IClient?

How can I do this? I have this same problem in many different projects.

Upvotes: 4

Views: 4790

Answers (2)

Saravana
Saravana

Reputation: 40584

While what you have added as answer might solve your problem, you can directly augment the Client interface and add the properties. You don't even need IClient. You can use module augmentation:

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

Upvotes: 8

Alexander Mills
Alexander Mills

Reputation: 100010

Wow, that wasn't so hard, I have been wondering how to do this for months.

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

we use the as notation to cast a generic type to a more specific type (I think that's the right way to put it).

I figure this out via this article: http://acdcjunior.github.io/typescript-cast-object-to-other-type-or-instanceof.html

Upvotes: 0

Related Questions