یادگیری تایپ اسکریپت در ۲۰۲۴

این روزها تایپ اسکریپت به محبوب‌ترین روش برای نوشتن جاوااسکریپت تبدیل شده است. بنابراین، اگر می‌خواهیم شغلی مرتبط با برنامه نویسی جاوااسکریپت پیدا کنیم لازم است که تایپ اسکریپت را بلد باشیم. در این مقاله سعی کردیم تا مجموعه‌ای از سوالات را گردآوری کنیم که برای تمرکز یادگیری روی مهم‌ترین بخش‌های تایپ اسکریپت طراحی شده است.

پیش‌نیازها

  • ما باید یک آشنایی در سطح مبتدی با جاوااسکریپت داشته باشیم. یعنی باید متغیرها، توابع، آبجکت‌ها و تمام بخش‌های بیسیک جاوااسکریپت را بدانیم.
  • همینطور لازم است که بدانیم که چگونه از خط فرمان استفاده کنیم. یعنی باید بتوانیم دستوراتی مانند
    npm install
    npm installو
    npm run build
    npm run buildرا اجرا کنیم.

مفاهیم بیسیک در تایپ اسکریپت

تایپ اسکریپت چیست؟

تایپ اسکریپت مجموعه‌ای از ابزارهایی است که نوشتن جاوااسکریپت را ساده‌تر می‌کند.

این ابزارها عبارتند از:

  • زبان تایپ اسکریپت که در فایل‌های
    .ts
    .tsو
    .tsx
    .tsxنوشته شده است.
  • کامپایلر تایپ اسکریپت که فایل‌های تایپ اسکریپت را از طریق
    tsc
    tscCLI به فایل‌های جاوااسکریپت تبدیل می‌کند.
  • سرور زبان تایپ اسکریپت، که تجربه تایپ اسکریپت را در IDE ما تقویت می‌کند.

می‌توانیم با مطالعه TypeScript’s Landing Page اطلاعات بیشتری در این زمینه کسب کنیم.

برای استفاده از تایپ اسکریپت به چه چیزی نیاز داریم؟

ما برای این که بتوانیم از تایپ اسکریپت استفاده کنیم باید Node.js را نصب کنیم. بهتر است برای نصب آن، نسخه LTS را انتخاب نماییم.

همچنین به یک ویرایشگر کد نیاز داریم که استفاده از VSCode توصیه می‌شود.

چرا به جای جاوااسکریپت، تایپ اسکریپت را انتخاب می‌کنیم؟

تایپ اسکریپت با دادن امکان تکمیل خودکار، خطاهای درون IDE و بسیاری از ویژگی‌های دیگر، IDE ما را قدرتمندتر می‌کند.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const user = {
firstName: "Angela",
lastName: "Davis",
role: "Professor",
};
console.log(user.name);
Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.
const user = { firstName: "Angela", lastName: "Davis", role: "Professor", }; console.log(user.name); Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.
const user = {
  firstName: "Angela",
  lastName: "Davis",
  role: "Professor",
};
 
console.log(user.name);
Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.

همچنین این احتمال وجود دارد که ایجاد باگ نیز کم‌تر شود. Airbnb در سال ۲۰۱۹، متوجه شد که ۳۸٪ از باگ‌هایی که تولید شده بود، اگر از تایپ اسکریپت استفاده می‌کردند با آن‌ها مواجه نمی‌شدند. برای کسب اطلاعات بیشتر این گفتگو را تماشا کنید.

آیا تایپ اسکریپت به درستی در مرورگر کار می‌کند؟

تایپ اسکریپت از سینتکسی استفاده می‌کند که در جاوااسکریپت native نیست. به عنوان مثال، تایپ اسکریپت یک کلمه کلیدی

type
typeدارد که در جاوااسکریپت این کلمه کلیدی وجود ندارد.

از آنجایی که مرورگرها فقط جاوااسکریپت را درک می‌کنند، نمی‌توانند فایل‌های تایپ اسکریپت را اجرا کنند.

این بدان معناست که برای استفاده از تایپ اسکریپت در وب، باید فایل‌های تایپ اسکریپت را قبل از ارسال به مرورگر به فایل‌های جاوااسکریپت تبدیل کنیم.

چگونه باید فایل‌های تایپ اسکریپت را به فایل‌های جاوااسکریپت تبدیل کنیم؟

برای کامپایل کردن فایل‌های تایپ اسکریپت در فایل‌های جاوااسکریپت، می‌توانیم از

tsc
tscCLI استفاده کنیم. برای این کار:

  • تایپ اسکریپت را با npm نصب می‌کنیم.
  • یک فایل
    tsconfig.json
    tsconfig.jsonرا به پروژه خود اضافه می‌کنیم (این فایل به تایپ اسکریپت می‌گوید چه کاری انجام دهد).
  • tsc
    tscرا اجرا می‌کنیم تا فایل‌های تایپ اسکریپت خود را در فایل‌های جاوااسکریپت کامپایل کنیم.

مطالعه راهنمای VSCode می‌تواند مفید باشد.

چگونه باید از تایپ اسکریپت برای ساخت برنامه‌های فرات‌اند مدرن استفاده کنیم؟

اگر بخواهیم یک اپلیکیشن فرانت‌اند بسازیم باید از فریم‌ورک فرانت‌اند استفاده کنیم. تقریباً هر فریم‌ورک مدرنی که انتخاب کنیم از تایپ اسکریپت OOTB(out of the box) پشتیبانی می‌کند.

اگر بین انتخاب فریم‌ورک‌ها مردد هستیم، Vite یک انتخاب عالی می‌تواند باشد. فریم‌ورک‌هایی مانند

Vite
Viteمسئولیت تبدیل فایل‌های
.ts
.tsبه فایل‌های
.js
.jsو همچنین بسیاری از موارد دیگر را بر عهده می‌گیرند.

این بدان معنی است که ما نیازی به اجرای دستی

tsc
tscنداریم. در این مورد مطالعه مستندات Vite همینطور مقاله آموزش نصب و استفاده از Vite می‌تواند مفید باشد.

چگونه باید از تایپ اسکریپت در CI استفاده کنید؟

استفاده از تایپ اسکریپت در CI یک راه عالی است که به ما این اطمینان را می‌دهد پروژه‌ای که داریم عاری از باگ خواهد بود. هنگامی که CI تنظیم شود، اگر پروژه هر گونه خطای تایپ اسکریپتی داشته باشد، CI با شکست مواجه می‌شود.

GitHub Actions یک راه عالی برای آزمایش این مورد است. اما ما می‌توانیم از تایپ اسکریپت در هر CI مبتنی بر لینوکس، مبتنی بر ویندوز یا MacOS استفاده کنیم. به طور کلی هر جایی که Node.js اجرا شود، می‌توانیم از تایپ اسکریپ هم استفاده کنیم.

تعاریف ضروری در تایپ اسکریپت

برای یادگیری بهتر این قسمت ابتدا بخش‌های ضروری سیستم تایپ تایپ اسکریپت را بررسی می‌کنیم.

تعریف پارامترهای یک تابع

اولین چیزی که بهتر است با آن آشنا شویم این است که چگونه تایپ‌ها را به پارامترهای یک تابع اضافه کنیم. این موضوع به ما این امکان را می‌دهد تا تایپ‌هایی را به تابع

greet
greetاضافه کنیم:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function greet(name: string) {
console.log(
"Hello, " + name.toUpperCase() + "!!"
);
}
function greet(name: string) { console.log( "Hello, " + name.toUpperCase() + "!!" ); }
function greet(name: string) {
  console.log(
    "Hello, " + name.toUpperCase() + "!!"
  );
}

به این ترتیب تابع

greet
greet تنها می‌تواند یک
string
stringرا به عنوان اولین آرگومان خود بپذیرد:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
greet(42);
Argument of type 'number' is not assignable to parameter of type 'string'.
greet(42); Argument of type 'number' is not assignable to parameter of type 'string'.
greet(42);
Argument of type 'number' is not assignable to parameter of type 'string'.

تایپ‌های بیسیک در تایپ اسکریپت

تایپ‌های اصلی تایپ اسریپت عبارتند از

string
string،
number
number،
boolean
booleanو
symbol
symbol. این‌ها نشان‌دهنده تایپ‌های اولیه هستند که زبان جاوااسکریپت را تشکیل می‌دهند.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let example1: string = "Hello World!";
let example2: number = 42;
let example3: boolean = true;
let example4: symbol = Symbol();
let example1: string = "Hello World!"; let example2: number = 42; let example3: boolean = true; let example4: symbol = Symbol();
let example1: string = "Hello World!";
let example2: number = 42;
let example3: boolean = true;
let example4: symbol = Symbol();

ما همچنین آن تایپ‌ها را به متغیرها اختصاص می‌دهیم. این بدان معنی است که تایپ اسکریپت به ما اجازه می‌دهد فقط یک

string
stringرا به
example1
example1، یک
number
numberرا به
example2
example2و غیره اختصاص دهیم.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
example1 = 42;
Type 'number' is not assignable to type 'string'.
example1 = 42; Type 'number' is not assignable to type 'string'.
example1 = 42;
Type 'number' is not assignable to type 'string'.

راهنمای تایپ اسکریپت اطلاعات بیشتری در مورد یادگیری strings، numbers و Booleans دارد. همینطور مطالعه مستندات MDN درمورد symbol می‌تواند مفید باشد.

تعریف مقدار بازگشتی یک تابع

ما همچنین می‌توانیم تایپ مقدار بازگشتی یک تابع را هم تعریف کنیم. این موضوع به ما این امکان را می‌دهد تا تایپ‌ها را به تابع

greet
greetاضافه کنیم:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function greet(name: string): string {
return "Hello, " + name.toUpperCase() + "!!";
}
function greet(name: string): string { return "Hello, " + name.toUpperCase() + "!!"; }
function greet(name: string): string {
  return "Hello, " + name.toUpperCase() + "!!";
}

این کد به ما اطمینان می‌دهد که تابع

greet
greetهمیشه یک
string
stringرا return می‌کند:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function greet(name: string): string {
return 123;
Type 'number' is not assignable to type 'string'.
}
function greet(name: string): string { return 123; Type 'number' is not assignable to type 'string'. }
function greet(name: string): string {
  return 123;
Type 'number' is not assignable to type 'string'.
}

مطالعه راهنمای تایپ اسکریپت می‌تواند برای یادگیری بهتر این بخش، مفید باشد.

تعریف آبجکت در تایپ اسکریپت

در مرحله بعد، باید به تایپ‌های آبجکت توجه کنیم. این‌ها به ما اجازه می‌دهند تا شکل یک آبجکت را توصیف کنیم.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function printCoord(pt: {
x: number;
y: number;
}) {
console.log(
"The coordinate's x value is " + pt.x
);
console.log(
"The coordinate's y value is " + pt.y
);
}
printCoord({ x: 3, y: 7 });
function printCoord(pt: { x: number; y: number; }) { console.log( "The coordinate's x value is " + pt.x ); console.log( "The coordinate's y value is " + pt.y ); } printCoord({ x: 3, y: 7 });
function printCoord(pt: {
  x: number;
  y: number;
}) {
  console.log(
    "The coordinate's x value is " + pt.x
  );
  console.log(
    "The coordinate's y value is " + pt.y
  );
}
printCoord({ x: 3, y: 7 });

مطالعه بخش Object Types تایپ اسکریپت برای این بخش بسیار مفید است. همچنین مطالعه بخش properties of objects optional نیز پیشنهاد می‌شود.

تعریف یک تایپ با قابلیت استفاده مجدد

ممکن است به این موضوع فکر کنیم که اگر یک تایپی داشته باشم که بخواهم در چندین قسمت مختلف از آن استفاده کنم، چه کاری باید انجام دهیم؟ آیا باید هر بار آن را از اول بنویسم؟

برای این کار می‌توانیم از کلمه کلیدی

type
typeاستفاده کنیم تا تایپ‌ها را برای استفاده‌های بعدی ذخیره کنیم:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {}
type Point = { x: number; y: number; }; function printCoord(pt: Point) {}
type Point = {
  x: number;
  y: number;
};
 
function printCoord(pt: Point) {}

این امکان در تایپ اسکریپت Type Aliases نام دارد.

تعریف آرایه در تایپ اسکریپت

ما می‌توانیم به دو روش مختلف آرایه‌ها را بنویسیم. روش اول با استفاده از سینتکس

[]
[]:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let example1: string[] = ["Hello World!"];
let example2: number[] = [42];
let example1: string[] = ["Hello World!"]; let example2: number[] = [42];
let example1: string[] = ["Hello World!"];
let example2: number[] = [42];

روش دوم با استفاده از سینتکس

Array<>
Array<>:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let example1: Array<string> = ["Hello World!"];
let example2: Array<number> = [42];
let example1: Array<string> = ["Hello World!"]; let example2: Array<number> = [42];
let example1: Array<string> = ["Hello World!"];
let example2: Array<number> = [42];

مطالعه راهنمای آرایه تایپ اسکریپت می‌تواند مفید باشد.

تعریف تاپل در تایپ اسکریپت

تاپل‌ها آرایه‌هایی با طول ثابت هستند که هر المنت دارای یک تایپ ثابت می‌باشد.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let example1: [string, number] = [
"Hello World!",
۴۲,
];
let example1: [string, number] = [ "Hello World!", ۴۲, ];
let example1: [string, number] = [
  "Hello World!",
  ۴۲,
];

می‌توانیم با مطالعه راهنمای تایپ اسکریپت درباره تاپل‌ها اطلاعات بیشتری کسب کنیم.

تعریف توابع در تایپ اسکریپت

می‌توانیم با استفاده از سینتکس

() => Type
() => Typeتوابع را تعریف کنیم:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
type MyFunction = () => string;
let example1: MyFunction = () => "Hello World!";
type MyFunction = () => string; let example1: MyFunction = () => "Hello World!";
type MyFunction = () => string;
 
let example1: MyFunction = () => "Hello World!";

این روش برای تعریف callbackهای ارسال شده به توابع دیگر مفید است:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function addEventListener(
event: string,
callback: () => void
) {
document.addEventListener(event, callback);
}
function addEventListener( event: string, callback: () => void ) { document.addEventListener(event, callback); }
function addEventListener(
  event: string,
  callback: () => void
) {
  document.addEventListener(event, callback);
}

می‌توانیم با مطالعه راهنمای تایپ اسکریپت اطلاعات بیشتری در مورد تایپ تابع بدست بیاوریم.

تعریف Setها و Mapها در تایپ اسکریپت

ما می‌توانیم setها و mapها را با استفاده از سینتکس

Set<Type>
Set<Type>و
Map<KeyType, ValueType>
Map<KeyType, ValueType>تعریف کنیم:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let example1 = new Set<string>();
example1.add(42);
Argument of type 'number' is not assignable to parameter of type 'string'.
let example2 = new Map<string, number>();
example2.set("id", "abc");
Argument of type 'string' is not assignable to parameter of type 'number'.
let example1 = new Set<string>(); example1.add(42); Argument of type 'number' is not assignable to parameter of type 'string'. let example2 = new Map<string, number>(); example2.set("id", "abc"); Argument of type 'string' is not assignable to parameter of type 'number'.
let example1 = new Set<string>();
 
example1.add(42);
Argument of type 'number' is not assignable to parameter of type 'string'.
 
let example2 = new Map<string, number>();
 
example2.set("id", "abc");
Argument of type 'string' is not assignable to parameter of type 'number'.

این سینتکس به ما این امکان را می‌دهد تا تایپ‌ها را به توابع ارسال کنیم. بدون این تایپ‌ها،

Map
Mapو
Set
Setنمی‌دانند چه تایپ‌هایی باید داشته باشند.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let example1 = new Set();
// No error!
example1.add(42);
example1.add("abc");
let example2 = new Map();
// No error!
example2.set("id", "abc");
let example1 = new Set(); // No error! example1.add(42); example1.add("abc"); let example2 = new Map(); // No error! example2.set("id", "abc");
let example1 = new Set();
 
// No error!
example1.add(42);
 
example1.add("abc");
 
let example2 = new Map();
 
// No error!
example2.set("id", "abc");

تعریف توابع Async در تایپ اسکریپت

می‌توانید توابع async را با استفاده از سینتکس

Promise<>
Promise<>تعریف کنیم:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
async function getGreeting(): Promise<string> {
return "Hello World!";
}
async function getGreeting(): Promise<string> { return "Hello World!"; }
async function getGreeting(): Promise<string> {
  return "Hello World!";
}

اگر از

Promise
Promiseاستفاده نکنیم، تایپ اسکریپت با خطا مواجه می‌شود:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
async function getGreeting(): string {
The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<string>'?
return "Hello World!";
}
async function getGreeting(): string { The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<string>'? return "Hello World!"; }
async function getGreeting(): string {
The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<string>'?
  return "Hello World!";
}

دیدگاه‌ها:

افزودن دیدگاه جدید