Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an alias of an interface from another module in typescript?

Tags:

typescript

I have 2 typescript files.

commons.d.ts

module "commons" {
    interface IUser {
        name:string;
    }
}

main.ts

import commons = module("commons");
class User implements commons.IUser {
    name:string;
}

Since I will use commons.User a lot in the main.ts, I want to create an alias for it. For I change the code to:

import commons = module("commons");

import UserAlias = commons.IUser;

class User implements UserAlias {
    name:string;
}

But it throws error when compiling:

E:\WORKSPACE\app\typescripts>tsc main.ts
E:/WORKSPACE/app/typescripts/main.ts(3,27): The property 'IUser'
    does not exist on value of type 'commons'
E:/WORKSPACE/app/typescripts/main.ts(3,19): A module cannot be aliased
    to a non-module type

How to fix it?

like image 856
Freewind Avatar asked Jan 26 '13 11:01

Freewind


1 Answers

To create an alias for an interface, you can extend it on a local interface:

I have tested this with:

commons.ts

export interface IUser {
    name: string;
}

app.ts

import commons = module("commons");

interface userAlias extends commons.IUser {
}

class User implements userAlias {
    name: string;
}

I have changed the commons.ts slightly because when you use External Modules don't usually have a module declaration inside of them - the file is the module. The module declaration is used for internal modules.

You can read more about that in section 9.4 of the TypeScript language specification.

like image 95
Fenton Avatar answered Oct 30 '22 03:10

Fenton