当前位置: 首页 > news >正文

面试题-在ts中类型转换的方法

在 TypeScript 中,类型转换主要分为 类型断言(Type Assertion)类型守卫(Type Guard) 和 类型兼容转换 三种方式。以下是详细分类和示例:

一、类型断言(Type Assertion)

强制编译器将值视为特定类型,不改变运行时行为。

1. 尖括号语法
let value: any = "hello";
let length: number = (<string>value).length;
2. as 语法(更推荐,JSX 中必须使用)
let value: any = "hello";
let length: number = (value as string).length;
3. 非空断言(Non-null Assertion)

断言值不为 null 或 undefined

function printLength(str: string | null) {console.log((str!).length); // 断言 str 不为 null
}

二、类型守卫(Type Guard)

在运行时检查类型,缩小类型范围。

1. typeof 守卫
function add(a: number | string, b: number | string): number {if (typeof a === "number" && typeof b === "number") {return a + b; // a 和 b 被缩小为 number}return Number(a) + Number(b);
}
2. instanceof 守卫
class Animal { speak() {} }
class Dog extends Animal { bark() {} }function printPet(pet: Animal) {if (pet instanceof Dog) {pet.bark(); // pet 被缩小为 Dog}
}
3. 自定义类型守卫
interface Fish { swim: () => void }
interface Bird { fly: () => void }function isFish(pet: Fish | Bird): pet is Fish {return (pet as Fish).swim !== undefined;
}function move(pet: Fish | Bird) {if (isFish(pet)) {pet.swim(); // 类型为 Fish} else {pet.fly();  // 类型为 Bird}
}

三、类型兼容转换

基于类型结构的隐式转换(无需断言)。

1. 子类型赋值给父类型
interface Animal { name: string }
interface Dog extends Animal { breed: string }let dog: Dog = { name: "Buddy", breed: "Labrador" };
let animal: Animal = dog; // 合法:Dog 是 Animal 的子类型
2. 联合类型转换
let value: string | number = "hello";
let str: string = value as string; // 断言为 string

四、类型转换工具类型

1. typeof

获取值的类型:

const person = { name: "Alice", age: 30 };
type PersonType = typeof person; // { name: string; age: number }
2. keyof

获取类型的所有属性名:

type PersonKeys = keyof typeof person; // "name" | "age"
3. 类型映射
type ReadonlyPerson = Readonly<typeof person>; // 所有属性变为只读

五、运行时类型转换

实际修改值的类型(与 TypeScript 类型系统无关)。

1. 转字符串
String(123);          // "123"
JSON.stringify({});   // "{}"
2. 转数字
Number("42");         // 42
parseInt("10px");     // 10
+"5";                 // 5(一元加号)
3. 转布尔值
Boolean(0);           // false
!!null;               // false(双重否定)

六、常见陷阱与最佳实践

  1. 过度使用断言

    • 避免使用 as any 绕过类型检查,优先使用类型守卫。
  2. 类型守卫与断言的区别

    • 类型守卫:运行时检查,真正缩小类型范围。
    • 类型断言:仅告知编译器类型,不验证值的实际类型。
  3. 使用类型谓词(Type Predicate)

    function isString(value: any): value is string {return typeof value === "string";
    }
    

总结

场景方法示例
强制类型转换(编译时)类型断言(as 或 <>)(value as string).length
运行时类型检查类型守卫(typeof/instanceof)if (typeof x === 'number') { ... }
获取已有类型typeoftype T = typeof obj
转换值的实际类型String()/Number()/Boolean()Number("42")
泛型约束extendsfunction identity<T extends string>(x: T)

合理使用这些工具,可以让你的 TypeScript 代码既安全又灵活。

http://www.lqws.cn/news/472987.html

相关文章:

  • Linux——Json
  • Unity Addressable使用之AddressableAssetSettings
  • MySQL误删数据急救指南:基于Binlog日志的实战恢复详解
  • Linux TCP/IP协议栈中的TCP输入处理:net/ipv4/tcp_input.c解析
  • 热成像仪测MOSFET温度
  • 国家级与省级(不含港澳台)标准地图服务网站汇总
  • swift-15-访问控制、内存管理
  • 【unitrix】 3.7 类型级加一计算(Add1.rs)
  • 第18章 泛型 todo
  • 将浮点数转换为分数
  • SimpleITK——创建nrrd体素模型
  • 三种语言写 MCP
  • C++ 的设计模式
  • [Python学习日记-93] 并发编程之多线程 —— 互斥锁与 Python GIL(Global Interpreter Lock)
  • 微处理器原理与应用篇---计算机系统的性能测试
  • 人工智能学习51-ResNet训练
  • 旧物回收小程序开发:开启绿色生活新方式
  • [TPAMI 2022]HGNN: General Hypergraph Neural Networks+
  • GO语言---数组
  • ffmpeg(七):直播相关命令
  • AI大模型学习之基础数学:高斯分布-AI大模型概率统计的基石
  • 4.1 FFmpeg编译选项配置
  • Wire--编译时依赖注入工具
  • Python元组常用操作方法
  • C++模板基础
  • 并查集(Disjoint-Set Union)详解
  • 【分布式理论】读确认数与写确认数:分布式一致性的核心概念
  • AI大模型学习之基础数学:微积分-AI大模型的数学引擎
  • 【Linux 平台总线驱动开发实战】
  • 湖北理元理律师事务所企业债务纾困路径:司法重整中的再生之道