סוגי נתונים ב-TypeScript
מאמר זה מסביר את סוגי הנתונים ב-TypeScript.
YouTube Video
סוגי נתונים ב-TypeScript
TypeScript מציעה מגוון סוגי נתונים. יכולת זו מאפשרת לך להגדיר סוגים מחמירים למשתנים, פרמטרים בפונקציות וערכי החזרה. להלן סוגי הנתונים העיקריים והשימוש בהם.
סוגי פרימיטיבים
סוג מספר (number)
1let age: number = 25;
2console.log(age); // Outputs: 25
3console.log(typeof age); // Outputs: number
מספר
הוא סוג שנועד להתמודד עם ערכים מספריים, כולל מספרים שלמים ומספרים עם נקודה עשרונית. טיפול בערכים שחורגים ממגבלות מסוימות יוביל ל-Infinity
אוNaN
(לא מספר).
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
-
ב-TypeScript, מספרים מיוצגים כמספרים בנקודה עשרונית. דבר זה עשוי להוביל לאי-דיוקים קלים בתוצאות החישוב.
-
כאשר נדרשים חישובים מדויקים, כמו סכומי כסף, יש להימנע משגיאות עיגול שכאלה. לדוגמה, ניתן להשתמש ב-
BigInt
אוtoFixed()
, או לכוונן את מספר הספרות העשרוניות באמצעות ספריות כמוdecimal.js
.
סוג מחרוזת (string)
סוג string
מטפל בנתוני טקסט.
1let greeting: string = "Hello, TypeScript!";
2console.log(greeting); // Outputs: Hello, TypeScript!
3console.log(typeof greeting); // Outputs: string
סוג בוליאני (boolean)
סוג boolean
מכיל שני ערכים: true
או false
.
1let isOpen: boolean = true;
2console.log(isOpen); // Outputs: true
3console.log(typeof isOpen); // Outputs: boolean
null ו-undefined
null
מייצג 'ערך שאינו קיים', ו-undefined
מייצג 'ערך לא מוגדר'.
1let emptyValue: null = null;
2let notDefined: undefined = undefined;
3
4console.log(emptyValue); // Outputs: null
5console.log(typeof emptyValue); // Outputs: object (JavaScript specification)
6
7console.log(notDefined); // Outputs: undefined
8console.log(typeof notDefined); // Outputs: undefined
Array
ב-TypeScript, ניתן להגדיר את סוג האלמנטים במערך. number[]
הוא מערך של מספרים, ו-string[]
הוא מערך של מחרוזות.
1let numbers: number[] = [1, 2, 3, 4];
2console.log(numbers); // Outputs: [1, 2, 3, 4]
3console.log(typeof numbers); // Outputs: object
4
5let words: string[] = ["TypeScript", "JavaScript"];
6console.log(words); // Outputs: ["TypeScript", "JavaScript"]
7console.log(typeof words); // Outputs: object
קבוצת ערכים (Tuple)
Tuple היא מערך עם אלמנטים מסוגים שונים.
1let person: [string, number] = ["Alice", 30];
2console.log(person); // Outputs: ["Alice", 30]
3console.log(typeof person); // Outputs: object
סוג מונה (Enum)
enum
מגדיר אוסף של קבועים עם שמות.
1enum Color {
2 Red,
3 Green,
4 Blue
5}
6
7let favoriteColor: Color = Color.Green;
8console.log(favoriteColor); // Outputs: 1 (Defaults start from 0)
9console.log(typeof favoriteColor); // Outputs: number
any
סוג any
יכול להכיל כל סוג של ערך ומשמש כאשר רוצים לבטל את בדיקת סוגי הנתונים.
1let anything: any = "Hello";
2console.log(anything); // Outputs: Hello
3console.log(typeof anything); // Outputs: string
4
5anything = 42;
6console.log(anything); // Outputs: 42
7console.log(typeof anything); // Outputs: number
סוג איחוד (Union)
באמצעות סוגי איחוד (Union) ניתן להגדיר משתנים שיכולים להכיל אחד מכמה סוגים.
1let identifier: number | string = "ID_12345";
2console.log(identifier); // Outputs: ID_12345
3console.log(typeof identifier); // Outputs: string
4
5identifier = 12345;
6console.log(identifier); // Outputs: 12345
7console.log(typeof identifier); // Outputs: number
סיכום
number
,string
,boolean
: סוגים פרימיטיביים.null
,undefined
: ערכים מיוחדים.מערך
: מערך עם ביאורי סוג.קְבוּצָה
: מערך עם אלמנטים מסוגים שונים.enum
: סוג ממוין.כָּל
: כל סוג.Union
: משתנה שיכול לקבל אחד מכמה סוגים.
באמצעות סוגי המידע הללו, TypeScript משפרת את בטיחות הסוגים ומקלה על מניעת שגיאות במהלך הפיתוח.
אובייקטים עוטפים
אובייקטי עיטוף ב-TypeScript הם אובייקטים שנוצרים אוטומטית כדי לטפל בסוגי נתונים בסיסיים כאובייקטים. סוגים בסיסיים מאפשרים פעולות קלות ומהירות, בעוד שסוגי אובייקטים כוללים שיטות ומאפיינים המאפשרים פעולות עשירות יותר.
ב-JavaScript (וב-TypeScript), ישנם אובייקטי עיטוף המתאימים לסוגים בסיסיים כמו string
, number
ו-boolean
. הם נוצרים באמצעות פונקציות בונים הנקראות בהתאמה String
, Number
, ו-Boolean
.
להלן דוגמאות לאובייקטי עיטוף.
אובייקט מחרוזת
אובייקט ה-String
מספק מאפיינים ושיטות למחרוזות.
1let strPrimitive: string = "Hello, World!";
2let strObject: String = new String("Hello, World!");
3
4console.log(strPrimitive); // Outputs: Hello, World!
5console.log(typeof strPrimitive); // Outputs: string
6
7console.log(strObject); // Outputs: [String: 'Hello, World!']
8console.log(typeof strObject); // Outputs: object
מאפיינים:
- בניגוד ל-
string
הבסיסי, אובייקטString
מטופל כ-object
על ידיtypeof
. - אובייקטי עיטוף שימושיים בעת מניפולציה על מחרוזות או בעת קריאה לשיטות עליהם.
אובייקט מספר
אובייקט ה-Number
מספק מאפיינים ושיטות למספרים.
1let numPrimitive: number = 42;
2let numObject: Number = new Number(42);
3
4console.log(numPrimitive); // Outputs: 42
5console.log(typeof numPrimitive); // Outputs: number
6
7console.log(numObject); // Outputs: [Number: 42]
8console.log(typeof numObject); // Outputs: object
מאפיינים:
- אובייקט ה-
Number
, כאובייקט עיטוף למספרים, כולל שיטות לפעולות מספריות (למשל,toFixed
).
אובייקט בוליאני
אובייקט ה-Boolean
מספק מאפיינים ושיטות לערכים בוליאניים.
1let boolPrimitive: boolean = true;
2let boolObject: Boolean = new Boolean(true);
3
4console.log(boolPrimitive); // Outputs: true
5console.log(typeof boolPrimitive); // Outputs: boolean
6
7console.log(boolObject); // Outputs: [Boolean: true]
8console.log(typeof boolObject); // Outputs: object
מאפיינים:
- אובייקט ה-
Boolean
הוא עיטוף לסוג הבסיסיboolean
ומטופל כ-object
.
הבדלים בין אובייקטי עיטוף לבין סוגים בסיסיים
מכיוון שאובייקטי עיטוף מטופלים כאובייקטים, ישנה ירידה קלה בביצועים, אך פעולות פונקציונליות נוספות מתאפשרות בשל תוספת של מאפיינים ושיטות. בנוסף, ישנם הבדלים בהשוואה באמצעות ==
ו-===
.
1let numPrimitive: number = 123;
2let numObject: Number = new Number(123);
3
4console.log('== : ', numPrimitive == numObject); // Outputs: true (Value comparison)
5console.log('=== : ', numPrimitive === numObject); // Outputs: false (Due to differing types)
מאפיינים:
==
משווה ערכים, בעוד ש-===
משווה בקפדנות כולל סוגים.===
מחזירfalse
כאשר משווים אובייקטים עטופים עם סוגים פרימיטיביים.
המרת סוגים
ב-TypeScript, חשוב לנהל כראוי המרות סוגים מרומזות ו-המרות סוגים מפורשות.
המרת סוגים מרומזת
- ב-TypeScript, יש להימנע ככל האפשר מהמרות סוגים מרומזות כדי להבטיח בטיחות סוגים.
1const result: string = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
- בדוגמה זו, המספר
5
מומר באופן מרומז למחרוזת, מה שמוביל למחרוזת"55"
.
המרת סוגים מפורשת
- ב-TypeScript, יש להשתמש בהערות סוג או בפונקציות להמרת סוגים כדי לבצע המרות סוגים באופן בטוח.
1const num: string = "123";
2const convertedNum: number = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
- בדוגמה זו, פונקציית
Number()
משמשת להמרת המחרוזת"123"
למספר123
באופן מפורש.
בדיקת סוגים
ב-TypeScript, ניתן להשתמש באופרטור typeof
כדי לבדוק את סוג הנתונים של משתנה.
1// Output: The type of 42 is: number
2console.log('The type of 42 is:', typeof 42);
3
4// Output: The type of 42 is: bigint
5console.log('The type of 42n is:', typeof 42n);
6
7// Output: The type of "hello" is: string
8console.log('The type of "hello" is:', typeof "hello");
9
10// Output: The type of true is: boolean
11console.log('The type of true is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol() is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {} is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
- ב-TypeScript, ניתן להשתמש ב-
typeof
לבדיקת סוגים, אך לבדיקת סוגים מדויקת יותר מומלץ גם להשתמש באופרטוריםinstanceof
אוis
.
סיכום
- אובייקטים עטופים נחשבים כאובייקטים מכיוון שהם מספקים שיטות ותכונות נוספות עבור סוגים פרימיטיביים.
String
,Number
ו-Boolean
הם דוגמאות מייצגות לאובייקטים עטופים.- בניגוד לסוגים פרימיטיביים, אובייקטים עטופים מזוהים כ-
object
על ידיtypeof
.
תוכלו לעקוב אחר המאמר שלמעלה באמצעות Visual Studio Code בערוץ היוטיוב שלנו. נא לבדוק גם את ערוץ היוטיוב.