TypeScript学习笔记5-类型别名

在 JavaScript 中,类型别名是一种自定义类型的方式,通过关键字 `type` 来创建。它允许你为现有的类型提供一个更具描述性的名称,从而增强代码的可读性和可维护性。类型别名通常与联合类型(Union Types)或交叉类型(Intersection Types)结合使用,以创建更复杂的类型。


1️⃣普通使用

我们可以简单的给username用到的string类型设置未userName

type userName = string

也可以使用联合类型命名一个可能是string也可能是string[ ]的类型

type studentName = string | stirng[ ]

 2️⃣更常使用到的地方是,给对象定义类型

比如 给“学生”类型student起别名

type student = {
    name:string,
    age:number
}

let statichit:student ={
    name:"statichit",
    age:21
}

 这里也可以使用接口中的描述属性比如?或readonly

3️⃣定义函数

type fn = (name: string, age: number) => string


let fn1: fn = function (name: string, age: number): string {
    return "xxx"
}

let fn2: fn = (name: string, age: number): string => "xxx"

在函数中使用

 (有点像java中的类)

// 定义类型别名
type UserID = string;
type UserName = string;
type User = {
  id: UserID;
  name: UserName;
};

// 使用类型别名
function printUserInfo(user: User) {
  console.log(`ID: ${user.id}, Name: ${user.name}`);
}

// 创建用户对象并传递给函数
const currentUser: User = {
  id: '123',
  name: 'John Doe'
};
printUserInfo(currentUser);

这里我们很容易发现,它和interface有点像,那么他们之间有什么区别么 

type与interface的区别

1.interface可以继承 type 只能通过 & 交叉类型合并

interface I1{
    name: string
}
interface I2 extends I1{
    age: string
}


type T1 = {
    name: string
}
type T2 = {
    age: number
}

let t:T1&T2 = {
    name:"张三",
    age: 12
}

2. type 可以定义 联合类型 和 可以使用一些操作符 interface不行

type nameType = string|string[]

interface只能以对象形式定义内容

3. interface 遇到重名的会自动合并 type 不行

interface A1 {
    name: string
}
// 遇到相同的会合并
interface A1{
    age: number
}

let a1:A1={
    name:"A1",
    age: 13
}

type A1 = {
    name: string
}

// 会直接报错
type A1 ={
    
}

类型别名作用:

  • 使代码更易读和易维护
  • 提高代码的可重用性
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值