'How to create an alias of an interface from another module in 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?
Solution 1:[1]
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.
Solution 2:[2]
You can always alias on importing:
import { IUser as userAlias } from "commons"
Ancient question, I know, but for anyone landing here now...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fenton |
| Solution 2 | fiddur |
