Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type reference without full namespace

Tags:

typescript

There are two typescript files:

A.ts:

export class Person {
    public name:string;
    constructor(){}
}

and

B.ts:

import A = module("A");
var p: A.Person;

So far everything works fine.

However, when I try to make a shortcut for the type name imported from the A.ts :

var Person = A.Person;
var pp: Person;

the compiler complains (on the line: "var pp: Person"):

The name 'Person' does not exist in the current scope

How can I achieve this or similar syntax, to avoid long namespaces?

like image 885
ads Avatar asked Mar 21 '13 07:03

ads


2 Answers

In TypeScript, the type annotation has to relate to a type known to the compiler. You can't just use variables as types. The alias you give to a module is the one you specify in the import statement - so you can alias from a long namespace to a short alias here:

import alias = module("My/Long/Module/Path");

But you do then have to use the alias.

To get the result you are looking for, you would have to use the slightly crazy local class extending the module class method:

import myModule = module("MyModule");

class Person extends myModule.Person {
}

var x: Person;
like image 183
Fenton Avatar answered Nov 09 '22 05:11

Fenton


I think the error you should get is "Type not defined" However currently the error is "The name does not exist in the current scope". Its because of separate declaration spaces for variables and types. A variable cannot be referenced in a type name section.

You can see it in a simple single file case here :

module M
{
    export interface P {}
}

import im = M; 
var foo1:im.P; // Okay 

var vm = M;
var foo2:vm.P; // Error 

However the solution to reduce the number of letters is inheritance as Steve mentioned.

like image 43
basarat Avatar answered Nov 09 '22 06:11

basarat