Exploring TypeScript Language Service Features with a Practical Example in Visual Studio Code

To illustrate the features of the TypeScript Language Service, let’s walk through a straightforward TypeScript example. Using Visual Studio Code (VS Code), a well-liked code editor for TypeScript development, we’ll construct a TypeScript file and investigate some of the features offered by the Language Service in this example.

Let’s say you want to write a TypeScript file that defines a class for the fundamental “Person” object. Here’s how to go about it:

Install TypeScript:

Using npm (Node Package Manager), you can install TypeScript globally if you haven’t already:

npm install -g typescript

Create a TypeScript File:

The following code should be added to a new TypeScript file, such as person.ts:

class Person {
constructor(public name: string, public age: number) {}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

const person1 = new Person("Alice", 30);
person1.greet();

We’ve constructed a basic Person class in this code, complete with a constructor and a greet method.

Visual Studio Code Integration:

In VS Code, choose the folder containing the TypeScript file. The TypeScript Language Service ought to be turned on by default.

IntelliSense and Type Checking:

As you type, IntelliSense offers auto-completion and type information suggestions. For instance, if you begin typing person1 after creating the person1 object, VS Code would suggest the greet method, name, and age attributes. TypeScript will display a type error if you attempt to assign a name or age value that is not a string or a number.

class Person {
constructor(public name: string, public age: number) {}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

const person1 = new Person("Alice", 30);

// IntelliSense and Type Checking Example
person1. // Place your cursor here and start typing

Suggestions for Properties and Methods from IntelliSense: The IntelliSense suggestions that appear when your cursor is over theperson1 object are based on the person1 object’s attributes and methods. Here, you ought to see recommendations for the name, age, and greet properties/methods.

Type checking while assigning values: Let’s show type checking in action. TypeScript will impose type checking if you begin to type a value to give to the name or age attributes. Examples include

person1.name = "Bob"; // Valid assignment because "name" is of type string
person1.age = 25; // Valid assignment because "age" is of type number

// Type Error: Uncommenting this line will result in a type error
// person1.name = 42; // Error: Type 'number' is not assignable to type 'string'

In this example, TypeScript allows you to assign valid values (strings and numbers) to the name and age properties, but it will display a type error if you attempt to assign a value of the incorrect type (for instance, a number to name).

Using IntelliSense to Call Methods: You can also invoke methods that have suggestions from IntelliSense. Consider this:

person1.greet(); // IntelliSense suggests "greet()"
person1.greet("Bob"); // IntelliSense suggests "greet(string)"

// Type Error: Uncommenting this line will result in a type error
// person1.greet(42); // Error: Argument of type '42' is not assignable to parameter of type 'string'

The greet method’s signature is suggested by IntelliSense provided by TypeScript. TypeScript will display a type error if you attempt to supply an argument that is the incorrect type (for example, a string rather than a number).

Navigation and documentation:

You can access the class definition by choosing “Go to Definition” from the context menu after right-clicking on a Person. Symbols can be quickly and easily researched by hovering over them.

Suppose you have the following TypeScript code in your person.ts file:

class Person {
constructor(public name: string, public age: number) {}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

const person1 = new Person("Alice", 30);

// Navigation and Documentation Example

Now, let’s explore navigation and documentation features:

Go to Definition:

  • Place your cursor over the Person class name.
  • Right-click (or use a keyboard shortcut) and select “Go to Definition” from the context menu.
  • Visual Studio Code will navigate to the definition of the Person class, which is located at the top of your file.
  • This feature is particularly helpful when you need to quickly jump to the source code of a class or symbol within your project.

Hover for Documentation

  • Hover your cursor over the name property inside the greet method.
  • Visual Studio Code will display a tooltip with documentation and quick information about the name property.
  • In this case, you can see that it’s a property of type string, and you get a brief description.
  • This feature is valuable for understanding the purpose and types of symbols in your codebase.

These navigation and documentation features within Visual Studio Code, powered by the TypeScript Language Service, help you explore your codebase, understand the relationships between different parts of your code, and access quick information about symbols, making it easier to navigate and work with complex projects.

Diagnostics:

TypeScript will highlight any errors you make, such as attempting to access a property that doesn’t exist, and will provide a diagnostic message. For instance, you will see the following issue if you alter person1.nam to person1.name:

class Person {
constructor(public name: string, public age: number) {}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

const person1 = new Person("Alice", 30);

// Intentionally introduce an error
person1.nam = "Bob"; // Should be "name" but we're using "nam"
person1.greet();

By attempting to access a field named nam on the person1 object that doesn’t exist in the Person class, we have introduced an error into this code. This error will be promptly highlighted by TypeScript, along with a diagnostic message.

  • TypeScript will underline the erroneous code with a red squiggly line, indicating that there’s a problem:
  • If you hover your cursor over the underlined code, TypeScript will display a diagnostic message explaining the issue:
    The error message reads: “Property ‘nam’ does not exist on type ‘Person’.”
  • Additionally, if you try to run this code, TypeScript will also provide an error in your development environment, indicating that there is a compilation error.

Your code will be accurate and maintainable because of TypeScript’s diagnostics feature, which enables you to identify and correct mistakes early in the development process.

Refactoring:

To rename symbols, utilize VS Code’s integrated refactoring tools. Renaming the class name using a right-click on Person and the option “Rename Symbol” will immediately update all references.

Eample:

class Person {
constructor(public name: string, public age: number) {}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

const person1 = new Person("Alice", 30);

Now, let’s rename the Person class to something else using the “Rename Symbol” refactoring feature:

  • Place your cursor on the Person class name, which you want to rename.
  • Right-click (or use the keyboard shortcut F2 on Windows/Linux or Cmd+F2 on macOS) on the Person class name
  • In the context menu that appears, select “Rename Symbol.”
  • After selecting “Rename Symbol,” VS Code will highlight the class name and provide an input field for you to enter the new name.
  • Enter the new name you want to use for the class. For example, let’s rename it to Human.
    Press Enter to confirm the rename.

Visual Studio Code will automatically update all references to the Person class throughout your code, including the class definition, constructor calls, and method calls.

After the rename, your code will look like this:

class Human {
constructor(public name: string, public age: number) {}

greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}

const person1 = new Human("Alice", 30);

The “Rename Symbol” refactoring feature in Visual Studio Code is an effective tool for swiftly and consistently renaming symbols in your codebase, ensuring that all references are updated properly, and it can support code consistency and readability.

You can also discover a lot about Javascript by exploring different topics.

Note: We welcome your feedback at Easy Coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!

One thought on “Exploring TypeScript Language Service Features with a Practical Example in Visual Studio Code

Leave a Reply

Your email address will not be published. Required fields are marked *