网站首页 > 文章精选 正文
今天我们往更实战、更贴近业务开发的方向走一步 —— 来看三个关键词:
对象类型
类型别名
类型安全的类(Class)
01|对象类型怎么定义?
在 JavaScript 里,我们经常写对象:
const product = {
name: "Table",
unitPrice: 450
}
在 TypeScript 中,我们可以为这种对象结构定义“类型”,也就是告诉 TS:
- 这个对象里有哪些字段
- 每个字段是什么类型
const product: { name: string; unitPrice: number } = {
name: "Table",
unitPrice: 450
}
小技巧:
- 属性之间可以用 ; 或 , 分隔;
- TS 通常也能自动推断对象的结构类型,但你手动加上更清晰、更安全。
02|想让属性变“可选”?加个问号就搞定!
有时候对象里的字段不是每次都有,比如:
type Product = {
name: string;
unitPrice?: number; // 可选字段
}
或者函数参数:
function getPrice(name: string, unitPrice?: number) {
// unitPrice 不是每次必须传
}
用 ? 表示「这个参数是可传可不传的」,TS 编译器不会报错,但你要记得在使用前判断它是否存在。
03|类型别名:用 type 关键字“起个名字”
如果你觉得对象类型太长,老是重复写不方便,可以用 type 创建一个“别名”:
type Product = {
name: string;
unitPrice?: number;
}
之后你就可以直接用 Product 来定义变量、参数类型、返回值等:
const table: Product = { name: "Desk", unitPrice: 999 };
还可以组合类型:
type Info = { createdAt: Date };
type ExtendedProduct = Product & Info;
记住:
- & 表示交叉类型,合并多个结构;
- | 表示联合类型,可能是 A 也可能是 B。
04|类(Class)也能加类型,让对象更结构化!
如果你更习惯“面向对象”的风格,TypeScript 支持你用类(Class)定义结构:
class Product {
name: string;
unitPrice: number;
constructor(name: string, unitPrice: number) {
this.name = name;
this.unitPrice = unitPrice;
}
getDiscountedPrice(discount: number): number {
return this.unitPrice * (1 - discount);
}
}
你也可以这样写得更简洁:
class Product {
constructor(
public name: string,
public unitPrice: number
) {}
getDiscountedPrice(discount: number): number {
return this.unitPrice * (1 - discount);
}
}
用 public 修饰参数时,TS 会自动创建属性并赋值!
总结小卡片来了!
概念 | 用途 | 备注 |
{} 对象类型 | 描述对象结构 | |
? 可选属性 | 属性或参数非必填 | |
type 别名 | 给复杂结构起名 | |
& 交叉类型 | 同时具备多个类型的属性 | |
| | 联合类型 | 可以是多种类型之一 |
class 类 | 面向对象建模 | |
类型注解 | 保证构造函数、方法参数、返回值类型一致 |
猜你喜欢
- 2025-05-14 TS,TypeScript,Windows环境下构建环境,安装、编译且运行
- 2025-05-14 TypeScript 也能开发AI应用了!
- 2025-05-14 搞懂 TypeScript 装饰器
- 2025-05-14 前端小哥哥:如何使用typescript开发实战项目?
- 2025-05-14 在 React 项目中,一般怎么处理错误?
- 2025-05-14 react19 常用状态管理
- 2025-05-14 Vue3开发极简入门(2):TypeScript定义对象类型
- 2025-05-14 C#与TypeScript语法深度对比
- 2025-05-14 360前端一面~面试题解析
- 2025-05-14 Python标准库中的七个“小众但神奇”的实用函数
- 05-14TS,TypeScript,Windows环境下构建环境,安装、编译且运行
- 05-14TypeScript 也能开发AI应用了!
- 05-14搞懂 TypeScript 装饰器
- 05-14前端小哥哥:如何使用typescript开发实战项目?
- 05-14在 React 项目中,一般怎么处理错误?
- 05-14react19 常用状态管理
- 05-14Vue3开发极简入门(2):TypeScript定义对象类型
- 05-14C#与TypeScript语法深度对比
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)