TypeScript: Migration from JavaScript - abeedal/Abeedal GitHub Wiki
TypeScript: Migration from JavaScript
TypeScript, a superset of JavaScript, is a strongly typed programming language that builds on JavaScript.
It adds additional syntax to JavaScript to support a tighter integration with and helps in catching coding errors early in the editor.
TypeScript code converts to JavaScript, which runs anywhere (i.e. in a browser, NodeJS , etc.).
Main benefits of TypeScript
Class and Module Support : Keywords like class, interface and module are available in TypeScript. A class can be defined as define as:
// define class in TypeScript class VirtualPageTracker extends Tracker { private virtualPageName: string = ''; constructor(name) { super(name); }
getName(): void { return this.virtualPageName; }
static getTrackerName(): string { return this.VirtualPageTracker; }
} NOTE: TypeScript will transcompile the above to JavaScript during runtime!
Static Type-checking: TypeScript compiler will check the type (to surface more typing errors at compile time). For example:
let name: string; name = 2; // type error, assign a number to a string type variable
function foo(value: number) { . . . } foo(''); // type error, use a number as a string type parameter
ES6 Feature Support: ES6 is the current version of the ECMAScript Language Specification with more language features. With TypeScript, we can start using many ES6 features although it may not be supported in our target browser. TypeScript compile can compile the .ts files into “ES3”, “ES5” or “ES6”. For example:
// for..of loops var arr = ['a', 'b', 'c']; for (let item of arr) { console.log(item); }
// using async & awaits in function, assertions, etc. help get rid of browser.pause(), etc.
Then(/^the "([^"]*)" CTA will be shown in the selected state$/, async (selectedCTA) {
let dateCTAIsSelected = await IndexScreen.dateCTAIsSelected(selectedCTA);
expect(dateCTAIsSelected).to.equals(true, The ${selectedCTA} is selected as expected.);
});
Clear Library API Definition: To let other TypeScript libraries use our library, we can create a .d.ts file to declare all our public types and APIs of our libraries. These definition files will turn out to be clear and accurate references of our public APIs since they are always maintained and update-to-date because we shall always need them as we a going to write our tests in TypeScript too.
Refer to GitHub - DefinitelyTyped/DefinitelyTyped: The repository for high quality TypeScript type definitions. for TypeScript definition files created for large amounts of JavaScript libraries.
Syntax Similarity to Our Backend Languages: ReactJS, JavaScript, etc.
Approaches:
- The easiest way to add TypeScript support to the existing projects involves using declaration files. A simple addition of d.ts file will help the TS compiler type-check existing JavaScript code and also give us auto-completion support in our IDE.
Add label