Now that more and more projects are using Typescript and enjoying its benefits, there are some best practices we can follow to use it more effectively. Here are some of the principles I use and recommend

Use the correct type declaration (avoid any)

Type declarations are one of Typescript’s great strengths, especially in the code phase. Because JavaScript defines types at runtime, Typescript helps you filter out a large number of weird types before they run. Do not use any when you know what type of variable you are defining. It is recommended to add the data type after each new variable.

name: string = "hello";
value: number = 50;
isCorrect: boolean = false;
Copy the code

Use strict mode

Use Strict is a feature added to JavaScript ES5, and it means exactly what it means: with strict mode, you can find the relevant configuration in the tsConfig file.

This prevents you from making unconscious or low-level mistakes, such as using undeclared variables, not using type annotations, or trying to use future reserved keywords as variable names. Use Strict helps you write good and safe code habits in the form of syntax errors.

Use let instead of var

Var is a good old friend, but let and const were introduced in ES6 to solve some problems with var.

Var can be applied to both global and local scopes.

  • whenvarWhen a type variable is defined outside of a function/block, it becomes a globally-scoped variable that can be used anywhere within the script
  • whenvarBecomes a local scope when defined inside a function, which can only be accessed inside the function
var name= "John Doe"; // Global scope
function getAge() {
  var age= 30; // local scope
}
Copy the code

The var keyword has several drawbacks: it can be declared repeatedly, can be called without being declared, and TS does not report errors, which can cause some strange problems.

var name = "John Doe";
function getName(){
    var name = "Anne"; // No error will be reported
}
Copy the code

To avoid this, use let instead. Let declares a block-level scoped variable and cannot be redeclared. But you can declare the same variable name in different scopes, and each is treated as a different variable.

let name = "John";
if (true) {
  let name = "Anne";
  console.log(name); // "Anne"
}
console.log(name); // "John"
Copy the code

Constant useConst statement

Const and let are new variable declarations together. Const is a block-level scoped type and, as such, cannot be redeclared. These are similarities between lets and const. The difference is that const cannot be reassigned. So when you declare a constant, use const.

const name = "John";
name = "Anne"; // error
const age = 30;
const age = 31; //error
Copy the code

PS: When we declare a const object, we cannot reassign to it, but we can modify its properties

Fixed – length arrays use tuple types

let marks: number[] = [1.2.3];
Copy the code

You can add as many elements to the Marks array as you want, so long as they are of type number, TS doesn’t limit you.

However, a constant array length can cause serious logic errors. To avoid this error, you can use tuple types to limit the length of the array and the data type of each item

let marks:[number.number] = [1.2]; // An array type containing two elements of type number
marks = [10.20]; / / success
marks = [1]; // Syntax error
marks = [1.2.3.4.5] // Syntax error
Copy the code

Using type aliases

Assume that multiple variables or objects have the same data structure type

let man: {name: string.age: number} = {name = "john", age=30};
let woman: {name: string.age: number} = {name = "Anne", age=32};
Copy the code

To avoid redundant type definitions you can use type aliases

type Details = {name: string.age: number}; // Define the type alias
let man: Details = {name = "john", age=30}; // Use the type alias
let woman: Details = {name = "Anne", age=32};
Copy the code

The added benefit is that the code is more readable and looks clearer

Any unknown and

On the surface, any and unknow are the same types of help we use when we are unsure of the data type. If we want to quickly refactor js into TS, we can do either, but there are some differences, right

Any value can be marked as any or unknown

let anyExample: any; // Define an any type
let unknownExample: unknown; // Define an unknown type
anyExample = 123; 
anyExample = "Hey"
unknownExample = false;
unknownExample = 23.22;
Copy the code

For the value marked any, you can do anything to it

anyExample.you.made.this.code.chain(); // success
Copy the code

Unknow doesn’t work, it’s a safer type

unknownExample.trim(); // Syntax error
Copy the code

To use an unknown type, you must place it in a conditional statement

if (typeof exampleUnkown == "string") { // First, check the type
  exampleUnkown.trim(); // No error will be reported
}
Copy the code

Use access modifiers on class members

TS provides access modifiers for class members. You can set public, protected, or private attributes, but class is always of public type

  • Private: Can only be accessed internally
  • Protected: Accessible internally or by subclasses
  • Public: both can be accessed
class Employee {
  protected name: string;
  private salary: number;
  
  constructor(name: string, salary: number) {
    this.name = name;
    this.salary = salary
  }

  public getSalary(){
    return salary
  }
}
Copy the code

To access the Salary property, you must call the getSalary method

class Developer extends Employee{
  viewDetails(){
    console.log(this.salary); // Error: Attribute 'salary' is private
    console.log(this.getSalary()); // success}}Copy the code

Access the name attribute through subclasses

class Developer extends Employee{
  viewDetails(){
    console.log(this.name); }}Copy the code

Using the Lint tool

Everyone has their own development style and habits, and multiple code styles can be disastrous on a team project. If you don’t want to contaminate your code base, you still need to choose a Lint tool. ESLint is preferred, which is compatible with both JavaScript and Typescript

Formatting code

Using a good code formatter can make your code more efficient and concise. From my personal experience, I prefer to use Prettier in VS code. But there are many code formatters, and the choice depends on the editor you’re using