3

For example, can we write using AMD?

define([
  'hb!./some/file.hb'
], function(template) {
  //
})

1 Answer 1

4

To some extent, yes.

Because TypeScript is just a superset of JavaScript, any valid JavaScript is also valid TypeScript.

In your example, the compiler would complain about define:

error TS2304: Cannot find name 'define'.

You need to tell the compiler that define exists before you use it:

declare var define;

define([
  'hb!./some/file.hb'
], function(template) {
  //
})

This will let the compiler know that define exists, but it does not provide the compiler with any additional information about it. So, another solution would be to add the proper type definition.

To consume amd modules, you will still need to include an amd module loader. That isn't something that is built into TypeScript. TypeScript is just a super set of JavaScript.

Using TypeScript enables compiler type checking, and allows you to use newer JavaScript features, while compiling to older versions of JavaScript. However, TypeScript won't be able to understand what it is that another module exports, therefore you will need a declaration for each AMD module describing what the module exports.

To that end, as another answer points out, you can also write modules using the ES6 syntax, and compile them to the amd format. From the documentation at TypeScriptLang.org:

Depending on the module target specified during compilation, the compiler will generate appropriate code for Node.js (CommonJS), require.js (AMD), isomorphic (UMD), SystemJS, or ECMAScript 2015 native modules (ES6) module-loading systems. For more information on what the define, require and register calls in the generated code do, consult the documentation for each module loader.

Sign up to request clarification or add additional context in comments.

1 Comment

But, in this case, one TypeScript can not infer types from the export of another AMD file like it can with ES6 modules. I think this would mean that I'd have to write a declaration alongside each and every AMD module file, which I was hoping not to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.