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

typescript中的type如何使用

在TypeScript中,type关键字用于创建类型别名。类型别名可以为任何类型提供一个新名字,这有助于使代码更加清晰和可维护。以下是一些使用type关键字的示例:

基本类型别名

type Age = number;
let myAge: Age = 30;

对象类型别名

type User = {id: number;name: string;
};
let user: User = {id: 1,name: "Alice",
};

联合类型

type Status = 'active' | 'inactive' | 'pending';
let currentStatus: Status = 'active';

元组类型

type Point = [number, number];
let coordinates: Point = [10, 20];

函数类型

type AddFunction = (a: number, b: number) => number;
let add: AddFunction = (a, b) => a + b;

字符串字面量类型

type CardinalDirection = 'North' | 'East' | 'South' | 'West';
let direction: CardinalDirection = 'North';

扩展类型

type BasicUser = {id: number;name: string;
};type ExtendedUser = BasicUser & {email: string;
};let extendedUser: ExtendedUser = {id: 1,name: "Bob",email: "bob@example.com",
};

映射类型

type ReadOnly<T> = {readonly [P in keyof T]: T[P];
};type ReadOnlyUser = ReadOnly<User>;let readOnlyUser: ReadOnlyUser = {id: 1,name: "Charlie",
};// Error: Cannot assign to 'id' because it is a read-only property.
// readOnlyUser.id = 2;

条件类型

type IsString<T> = T extends string ? true : false
type IsStringResult = IsString<string>; // true
type IsNumberResult = IsString<number>; // false

这些只是type关键字在TypeScript中的一些基本用法。类型别名可以极大地提高代码的可读性和可维护性,特别是在处理复杂的类型时。

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

相关文章:

  • FSC认证概述?FSC认证的核心原则与标准?FSC认证的市场价值与意义
  • QRSuperResolutionNet:一种结构感知与识别增强的二维码图像超分辨率网络(附代码解析)
  • SSH登陆Linux常见问题大全
  • RAMSUN分享全新超值型MM32F0050系列MCU
  • 航芯MCU使用IAR+Jlink调试
  • 关于单片机的基础知识(一)
  • yFiles:专业级图可视化终极解决方案
  • Maskrcnn网络结构学习
  • DataStreamAPI实践原理——快速上手(实操详细版)
  • AbMole|Temozolomide在胶质母细胞瘤研究中为什么会常用到?
  • 300道GaussDB(WMS)题目及答案。
  • 2506,wtl的通知事件
  • LangChain开发环境搭建
  • 【Linux系统】命令行参数 和 环境变量(含内建命令介绍)
  • 行为型-迭代器模式
  • 主流Agent开发平台学习笔记:扣子罗盘coze loop 功能拆解
  • 68 VG的基本信息查询
  • Visual Studio如何引入第三方头文件——以部署OpenGL为例
  • 综合案例:斗地主
  • 【算法训练营Day06】哈希表part2
  • 基于单片机的FFT的频谱分析仪设计
  • css实现圆环展示百分比,根据值动态展示所占比例
  • Haystack:AI与IoT领域的全能开源框架
  • 【conda配置深度学习环境】
  • PhpStorm设置中文
  • Monorepo架构: 项目管理工具介绍、需求分析与技术选型
  • 西肯麦远程数据通讯架构说明
  • 实战解析MCP-使用本地的Qwen-2.5模型-AI协议的未来?
  • 让AI看见世界:MCP协议与服务器的工作原理
  • 【C/C++】入门grpc的idl