Typescript Deep Dive by Basarat Ali Syed
Typescript Deep Dive by Basarat Ali Syed
Typescript Deep Dive by Basarat Ali Syed
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
TypeScript <strong>Deep</strong> <strong>Dive</strong><br />
This is because foo is used as a variable.<br />
Use case: Lazy loading<br />
Type inference needs to be done upfront. This means that if you want to use some type from a file foo in a file bar you<br />
will have to do:<br />
import foo = require('foo');<br />
var bar: foo.SomeType;<br />
However you might want to only load the file foo at runtime under certain conditions. For such cases you should use the<br />
import ed name only in type annotations and not as a variable. This removes any upfront runtime dependency code being<br />
injected <strong>by</strong> TypeScript. Then manually import the actual module using code that is specific to your module loader.<br />
As an example, consider the following commonjs based code where we only load a module 'foo' on a certain function call<br />
import foo = require('foo');<br />
export function loadFoo(){<br />
// This is lazy loading `foo` and using the original module *only* as a type annotation<br />
var _foo: typeof foo = require('foo');<br />
// Now use `_foo` as a variable instead of `foo`.<br />
}<br />
A similar sample in amd (using requirejs) would be:<br />
import foo = require('foo');<br />
export function loadFoo(){<br />
// This is lazy loading `foo` and using the original module *only* as a type annotation<br />
require(['foo'], (_foo: typeof foo) => {<br />
// Now use `_foo` as a variable instead of `foo`.<br />
});<br />
}<br />
This pattern is commonly used:<br />
in web apps where you load certain JavaScript on particular routes<br />
in node applications where you only load certain modules if needed to speed up application bootup.<br />
Use case: Breaking Circular dependencies<br />
Similar to the lazy loading use case certain module loaders (commonjs/node and amd/requirejs) don't work well with<br />
circular dependencies. In such cases it is useful to have lazy loading code in one direction and loading the modules upfront<br />
in the other direction.<br />
Fork me on github<br />
File Module Details<br />
45