ts和js的区别
- Ts是Js的超集,在JS基础上增加了静态类型检查
- 核心优势:编译期类型检查,把运行期错误提前暴露
- 开发体验:智能提示更好,代码重构更安全
- 但注意:TypeScript最终会编译成JavaScript运行,浏览器不直接识别TS
TypeScript 有哪些基础类型
// 基础类型
boolean, number, string, array, tuple, enum, any,
void, null, undefined, never, object
// 示例
let isDone: boolean = false;
let age: number = 25;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ['hello', 10];
enum Color {Red, Green, Blue}
什么是泛型?如何理解和使用泛型?
interface 和 type 的区别是什么?
interface 侧重于描述对象结构,支持声明合并;type 更灵活,可以为任何类型起别名
扩展方式不同
interface用extendstype用&(交叉类型)
重复声明行为不同
interface可以重复声明自动合并type重复声明会报错
适用类型范围不同
interface只能描述对象类型type可以描述任何类型(原始类型、联合类型、元组等)
优先用 interface,需要用到联合类型或工具类型时再用 type。
联合类型和交叉类型
什么是类型守卫?有哪些类型守卫的方法?
// 1. typeof 守卫
function print(value: string | number) {
if (typeof value === 'string') {
console.log(value.toUpperCase())
}
}
// 2. instanceof 守卫
class Dog { bark() {} }
class Cat { meow() {} }
function speak(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark()
}
}
// 3. 自定义类型守卫
interface Fish { swim(): void }
interface Bird { fly(): void }
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined
}