Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use namespace as type in typescript

Tags:

typescript

I have installed type definitions for google maps that declares a namespace like this:

namespace google.maps {   export class Map {     // ...   }    // ... } 

So if i just use the API globally it works beautifully:

const map = new google.maps.Map(); 

For unit testablity I don't want to access the API globally but instead inject it. But it seems I can't type that a variable should by from type google.map

So this doesn't work:

function mapFactory(api: google.maps) {     return new api.Map(); } 

Any solution how to use the namespace as a type?

like image 727
sod Avatar asked Mar 15 '17 16:03

sod


People also ask

Should you use namespace in TypeScript?

This ultra-famous book about typescript states: For most projects we recommend using external modules and using namespace for quick demos and porting old JavaScript code. TSLint has a predefined rule to avoid namespaces.

What is the difference between namespace and module in TypeScript?

A module is a way which is used to organize the code in separate files and can execute in their local scope, not in the global scope. A namespace is a way which is used for logical grouping of functionalities with local scoping.

What is declare namespace?

Namespace Declaration We can create a namespace by using the namespace keyword followed by the namespace_name. All the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword. The export keyword makes each component accessible to outside the namespaces.

Which of the following is possible when using namespaces but not when using modules?

Using Namespaces Unlike modules, they can span multiple files, and can be concatenated using outFile .


1 Answers

Try:

function mapFactory(api: typeof google.maps) {     return new api.Map(); } 
like image 174
Nitzan Tomer Avatar answered Sep 21 '22 19:09

Nitzan Tomer