Загрузка...

TypeScript - Understanding Type Annotation and Type Inference

In TypeScript, two very important concepts are Type Annotation and Type Inference.
These help TypeScript understand the type of data (string, number, boolean) used in your program.

Type Annotation (Explicit Type)
--------------------------------
Type Annotation means you explicitly tell TypeScript what the type of a variable or function
should be.

You manually specify the type.
Example
let username: string = "Deepak";
let age: number = 45;
let isTrainer: boolean = true;

Explanation:
username: string → username must store a string
age: number → age must store a number
isTrainer: boolean → true or false only

If you try this:
username = 100;

TypeScript will give an error:
Type 'number' is not assignable to type 'string'
So Type Annotation improves code safety.
Example with Function
function add(a: number, b: number): number {
return a + b;
}

Here we annotated:
a: number
b: number
: number → return type
Type Inference (Automatic Type)
================================
Inference means the process of arriving at a certain conclusion using reasoning or evidence,
which makes them more than just assumptions
Type Inference means TypeScript automatically guesses the type based on the value assigned.

You do not write the type manually.

Example
let city = "London";

TypeScript automatically infers:

city: string

Another example:
let price = 100;

TypeScript infers:
price: number

If you try:
price = "hello";

You will get an error because TypeScript already inferred number.
Pro Tip
---------
In real projects, developers usually use Type Inference for variables.
and Type Annotation for function parameters.

Type Annotation improves code clarity,
while Type Inference reduces unnecessary typing and keeps code clean.
#typescript #typescripttutorial #playwrightwithtypescript #playwrighttutorial #automationtesting #automationtestinginterviewquestions
#qatraining #letslearnqa

Видео TypeScript - Understanding Type Annotation and Type Inference канала Lets Learn QA
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять