Default exports

Default exports

Each module can optionally export a default export. Default exports are marked with the keyword default; and there can only be one default export per module. default exports are imported using a different import form.

default exports are really handy. For instance, a library like JQuery might have a default export of jQuery or $, which we’d probably also import under the name $ or jQuery.

JQuery.d.ts
1
2
declare let $: JQuery;
export default $;
App.ts
1
2
3
import $ from "JQuery";
 
$("button.continue").html( "Next Step..." );

Classes and function declarations can be authored directly as default exports. Default export class and function declaration names are optional.

ZipCodeValidator.ts
1
2
3
4
5
6
export default class ZipCodeValidator {
  static numberRegexp = /^[0-9]+$/;
  isAcceptable(s: string) {
    return s.length === 5 && ZipCodeValidator.numberRegexp.test(s);
  }
}
Test.ts
1
2
3
import validator from "./ZipCodeValidator";
 
let myValidator = new validator();

or

StaticZipCodeValidator.ts
1
2
3
4
5
const numberRegexp = /^[0-9]+$/;
 
export default function (s: string) {
  return s.length === 5 && numberRegexp.test(s);
}
Test.ts
1
2
3
4
5
6
7
8
import validate from "./StaticZipCodeValidator";
 
let strings = ["Hello", "98052", "101"];
 
// Use function validate
strings.forEach(s => {
  console.log(`"${s}" ${validate(s) ? " matches" : " does not match"}`);
});

default exports can also be just values:

OneTwoThree.ts
1
export default "123";
Log.ts
1
2
3
import num from "./OneTwoThree";
 
console.log(num); // "123"
doc_TypeScript
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.