TypeScript运算符详解
编程小白也能轻松理解的运算符知识汇总
📝 运算符是什么?
运算符就像数学中的加减乘除符号一样,是用来对数据进行操作的符号。比如说,我们用 + 来加两个数字,用 – 来减两个数字。在TypeScript中,运算符的功能更丰富,可以用来操作各种类型的数据。
💡 TypeScript的运算符大部分和JavaScript一样,但增加了更强的类型检查功能,让我们在编写代码时能更早地发现错误。
🧮 算术运算符
加法运算符 (+)
用于数字相加或字符串拼接
+
let sum = 10 + 5; // 15
let fullName = “张” + “三”; // “张三”
let fullName = “张” + “三”; // “张三”
️ 注意:当字符串和数字相加时,数字会被转换成字符串,如:”5″ + 10 结果是 “510”
减法运算符 (-)
用于数字相减
–
let difference = 10 – 5; // 5
let negative = 5 – 10; // -5
let negative = 5 – 10; // -5
乘法运算符 (*)
用于数字相乘
*
let product = 10 * 5; // 50
let zero = 10 * 0; // 0
let zero = 10 * 0; // 0
除法运算符 (/)
用于数字相除
/
let quotient = 10 / 5; // 2
let fraction = 5 / 2; // 2.5
let fraction = 5 / 2; // 2.5
📏 比较运算符
等于 (==) 和严格等于 (===)
检查两个值是否相等
== 和 ===
5 == “5” // true(值相等)
5 === “5” // false(类型不同)
5 === 5 // true
5 === “5” // false(类型不同)
5 === 5 // true
💡 在TypeScript中,强烈推荐使用 ===,因为它同时比较值和类型,更安全
不等于 (!=) 和严格不等于 (!==)
检查两个值是否不相等
!= 和 !==
5 != “5” // false(值相等)
5 !== “5” // true(类型不同)
5 !== “5” // true(类型不同)
大于 (>) 和小于 (<)
比较数值大小
> 和 <
10 > 5 // true
5 < 10 // true
5 > 10 // false
5 < 10 // true
5 > 10 // false
大于等于 (>=) 和小于等于 (<=)
比较数值大小(包含等于)
>= 和 <=
10 >= 10 // true
5 <= 10 // true
5 >= 10 // false
5 <= 10 // true
5 >= 10 // false
🔍 逻辑运算符
逻辑与 (&&)
当所有条件都为true时返回true
&&
true && true // true
true && false // false
false && false // false
true && false // false
false && false // false
💡 实际应用中常用于多个条件同时满足的情况,如:if(age > 18 && hasLicense)
逻辑或 (||)
当任意一个条件为true时返回true
||
true || false // true
false || true // true
false || false // false
false || true // true
false || false // false
逻辑非 (!)
取反操作,把true变false,false变true
!
!true // false
!false // true
!(10 > 5) // false
!false // true
!(10 > 5) // false
空值合并运算符 (??)
当左侧值为null或undefined时,返回右侧值
??
let name = null ?? “无名氏”; // “无名氏”
let age = 0 ?? 18; // 0(因为0不是null或undefined)
let age = 0 ?? 18; // 0(因为0不是null或undefined)
💡 与 || 的区别:?? 只判断null/undefined,而 || 会判断所有假值(0、”、false等)
📝 赋值运算符
基本赋值 (=)
给变量赋值
=
let age = 25;
let name = “张三”;
let name = “张三”;
加等于 (+=)
给变量加上一个值并重新赋值给它
+=
let count = 10;
count += 5; // 等价于 count = count + 5;
// 现在 count 是 15
count += 5; // 等价于 count = count + 5;
// 现在 count 是 15
减等于 (-=)
给变量减去一个值并重新赋值给它
-=
let money = 100;
money -= 30; // 等价于 money = money – 30;
// 现在 money 是 70
money -= 30; // 等价于 money = money – 30;
// 现在 money 是 70
乘等于 (*=)
变量乘以一个值并重新赋值给它
*=
let price = 10;
price *= 1.2; // 等价于 price = price * 1.2;
// 现在 price 是 12(涨价20%)
price *= 1.2; // 等价于 price = price * 1.2;
// 现在 price 是 12(涨价20%)
⚡ TypeScript特有运算符
可选链操作符 (?.)
安全地访问深层嵌套的对象属性
?.
// 避免user.address为null时出错
let street = user?.address?.street;
// 如果user或address为null/undefined,则返回undefined
// 不会抛出错误
let street = user?.address?.street;
// 如果user或address为null/undefined,则返回undefined
// 不会抛出错误
💡 再也不用担心”无法读取undefined的属性”的错误了!
非空断言操作符 (!)
告诉TS编译器某个值一定不为null/undefined
!
// 我们知道inputElement一定有值
const input = document.getElementById(‘input’)!;
// 告诉TS用户一定有名字
function greet(user: {name?: string}) {
console.log(`你好, ${user.name!}`);
}
const input = document.getElementById(‘input’)!;
// 告诉TS用户一定有名字
function greet(user: {name?: string}) {
console.log(`你好, ${user.name!}`);
}
⚠️ 使用时要谨慎!如果实际上值为空,程序会崩溃
类型断言
告诉TS某个值的确切类型
<Type> 或 as Type
// 两种写法:
let strLength1: number = (<string>someValue).length;
let strLength2: number = (someValue as string).length;
// 常用于处理来自外部的不确定类型数据
let strLength1: number = (<string>someValue).length;
let strLength2: number = (someValue as string).length;
// 常用于处理来自外部的不确定类型数据
💡 类型断言不是类型转换,只是在编译阶段起作用
类型守卫 (typeof / instanceof)
在条件分支中缩小变量类型范围
typeof / instanceof
function printId(id: number | string) {
if (typeof id === “string”) {
// 这里id是string类型
console.log(id.toUpperCase());
} else {
// 这里id是number类型
console.log(id);
}
}
if (typeof id === “string”) {
// 这里id是string类型
console.log(id.toUpperCase());
} else {
// 这里id是number类型
console.log(id);
}
}
🔧 其他常用运算符
三元条件运算符 (? 🙂
简单的if-else语句的简写形式
? :
let age = 20;
let status = age >= 18 ? “成年人” : “未成年人”;
// 等价于:
// if (age >= 18) status = “成年人”;
// else status = “未成年人”;
let status = age >= 18 ? “成年人” : “未成年人”;
// 等价于:
// if (age >= 18) status = “成年人”;
// else status = “未成年人”;
💡 适合简单的条件赋值,复杂逻辑还是用if-else更清晰
递增 (++) 和递减 (–)
给数字变量加1或减1
++ 和 —
let count = 0;
count++; // 现在count是1
count–; // 现在count是0
// 前缀和后缀的区别:
let a = 5;
let b = a++; // b = 5, a = 6
let c = ++a; // c = 7, a = 7
count++; // 现在count是1
count–; // 现在count是0
// 前缀和后缀的区别:
let a = 5;
let b = a++; // b = 5, a = 6
let c = ++a; // c = 7, a = 7
展开运算符 (…)
展开数组或对象
…
// 数组展开
let arr1 = [1, 2, 3];
let arr2 = […arr1, 4, 5]; // [1,2,3,4,5]
// 对象展开
let obj1 = { a: 1, b: 2 };
let obj2 = { …obj1, c: 3 }; // {a:1, b:2, c:3}
let arr1 = [1, 2, 3];
let arr2 = […arr1, 4, 5]; // [1,2,3,4,5]
// 对象展开
let obj1 = { a: 1, b: 2 };
let obj2 = { …obj1, c: 3 }; // {a:1, b:2, c:3}
typeof 运算符
获取变量或值的类型
typeof
console.log(typeof 42); // “number”
console.log(typeof ‘hello’); // “string”
console.log(typeof true); // “boolean”
// TypeScript中也可以用来获取类型别名
type Point = { x: number, y: number };
type P = typeof Point; // { x: number, y: number }
console.log(typeof ‘hello’); // “string”
console.log(typeof true); // “boolean”
// TypeScript中也可以用来获取类型别名
type Point = { x: number, y: number };
type P = typeof Point; // { x: number, y: number }
💎 总结:运算符使用要点
🚀 运算符优先级
就像数学中乘除优先于加减一样,运算符有优先级顺序:
1. 括号 () 优先级最高
2. 一元运算符(如 !, ++, –, typeof)
3. 乘除 */
4. 加减 +-
5. 比较运算符 > < >= <=
6. 相等运算符 == != === !==
7. 逻辑与 &&
8. 逻辑或 ||
9. 三元运算符 ? :
10. 赋值运算符 = += -= 等
2. 一元运算符(如 !, ++, –, typeof)
3. 乘除 */
4. 加减 +-
5. 比较运算符 > < >= <=
6. 相等运算符 == != === !==
7. 逻辑与 &&
8. 逻辑或 ||
9. 三元运算符 ? :
10. 赋值运算符 = += -= 等
💡 不确定优先级时,使用括号 () 来明确运算顺序是最安全的做法!
✅ 最佳实践建议
1. 比较时优先使用 === 而不是 ==
2. 使用 ?? 替代 || 来处理可能的null/undefined值
3. 多用可选链 ?. 避免深层属性访问错误
4. 逻辑运算符 && 和 || 可用于条件执行
5. 谨慎使用非空断言 ! ,确保值不为空
6. 复杂表达式使用括号明确优先级
7. TypeScript特有运算符充分利用类型系统优势
8. 避免在复杂表达式中混合多种运算符
2. 使用 ?? 替代 || 来处理可能的null/undefined值
3. 多用可选链 ?. 避免深层属性访问错误
4. 逻辑运算符 && 和 || 可用于条件执行
5. 谨慎使用非空断言 ! ,确保值不为空
6. 复杂表达式使用括号明确优先级
7. TypeScript特有运算符充分利用类型系统优势
8. 避免在复杂表达式中混合多种运算符
TypeScript运算符汇总 | 编程小白入门指南 | 使用通俗易懂的语言讲解
通过掌握这些运算符,您已经打下了坚实的TypeScript基础!