Wednesday, March 22, 2017

the default keyword in TypeScript

If color-pattern.enum.ts looks like this:

export enum ColorPattern {
   Solid,
   Splotchy,
   Striped
}

 
 

Then snake.model.ts in the same folder could loop it in like this:

import { ColorPattern } from './color-pattern.enum';
export class Snake {
   commonName: string;
   genusAndSpecies: [string,string];
   lengthInMeters: number;
   appearance: ColorPattern;
}

 
 

But if it looks like this:

export default enum ColorPattern {
   Solid,
   Splotchy,
   Striped
}

 
 

It must be looped in like this:

import ColorPattern from './color-pattern.enum';
export class Snake {
   commonName: string;
   genusAndSpecies: [string,string];
   lengthInMeters: number;
   appearance: ColorPattern;
}

 
 

The default keyword makes it so that there may only be one type per file and not a collection and that means you cannot import it (the one and only thing) with the curly braces as you might a collection. If there are multiple things in a file (and, obviously none of them have the default keyword decorating them) you may use one import statement to import them all (or just the ones you want) while comma separating the items inside the curly braces like so:

import { ColorPattern, SomethingElse } from './color-pattern.enum';
export class Snake {
   commonName: string;
   genusAndSpecies: [string,string];
   lengthInMeters: number;
   appearance: ColorPattern;
   somethingMore: SomethingElse;
}

 
 

This takes some getting used to. It will seem as if lines of codes where you are importing things are mad (can't compile) for no reason because of stupid mistakes with the default keyword.

No comments:

Post a Comment