Key features of typescript
- Statically typed language.
- Helps to detect errors including typos at run time.
- Offer additional features generics, interfaces, and enums.
Installing and compilation using typescript
- The TypeScript compiler is available as an npm package
- After installation one can start creating TypeScript files(*.ts).
- The compiler compiles the .ts files into standard .js
Typescript with LWC
Lightning Web Components has basic support for TypeScript. Type checking is not possible between js files and Html and even deployed typescript code can not be processed by the lwc platform compiler. To overcome this one can use vs code’s language service and use the lesser strict levels of typescript.
The level of typescript according to its strictness goes on increasing as mentioned below
- Using //@ts-check at beginning of the js file or using checkjs in checkjs in compilerOptions in jsconfig.json file.
- A type system based only on interference with js code.
- Using incremental typing with JSDoc https://www.typescriptlang.org/docs/handbook/jsdoc-supporte d-types.html
- Typescript code
- Typescript with strict enabled
Using typescript in VS code for LWC
- Specify the types using JSDoc constructs.
- To enable type checking add //ts-check at beginning of the js file.
- VS code will show an error as in the below example
One can also enable type checking for all js files by adding “checkJs”: true in the jsconfig.json file. Also, make sure you set “ESNext” as a target to prevent errors from showing up on ES5+ features like get/set accessors.
Benefits of Typescripts
- Strong Static Typing- It is a strongly typed language ie. if no type is declared for a variable it is inferred by TLS based on its value.
- OOP’s – supports concepts like interfaces, inheritance, etc.
Usage of typescript with its strict levels usage is increasing within the community to write clean and robust code. Using typescript can avoid future run-time errors and lead to a lesser no of bugs in application development.