【TypeScript】TypeScript语法细节

💭💭

✨:TypeScript语法细节

💟:东非不开森的主页

💜: 积极向上才是最好的状态💜💜

🌸: 如有错误或不足之处,希望可以指正,非常感谢😉

TypeScript

    • 一、语法
      • 1.1.ts联合类型
      • 1.2.ts交叉类型
      • 1.3.ts类型别名
      • 1.4.ts接口声明使用
      • 1.5.ts类型断言
      • 1.6.ts非空类型断言
      • 1.7.ts中字面量类型
      • 1.8.ts类型缩小

一、语法

⭐⭐⭐⭐

1.1.ts联合类型

  • 联合类型是由两个或者多个其他类型组成的类型,
  • 使用 | 符号
  • 联合类型中的每一个类型被称之为联合成员
let foo: number | string = 'aa'

1.2.ts交叉类型

  • 交叉类似表示需要满足多个类型的条件
  • 使用 & 符号
// 两种类型同时满足
interface KKPerson {name: stringage: number
}
interface ZZPerson {name: stringlover: () => void
}type InfoType = KKPerson & ZZPerson
const info: InfoType = {name: "kk",age: 18,lover: function() {console.log("loving")}
}

1.3.ts类型别名

类型别名(Type)

  • 可以给类型起一个别名

  • Type类型不能出现重复定义

  • 接口类型定义的类型也可以使用Type定义

type kkNumber = number
const age: kkNumber = 18

1.4.ts接口声明使用

⭐⭐⭐
接口类型(Interface)

  • 接口类型可以给对象 / 函数等定义类型

  • 接口是可以实现多个接口

  • 接口也可以被类实现(继承)

// 接口:interface
// 声明的方式
interface KKType {x: numbery: numberz?:number
}
function coord(point: KKType) {}

类型别名type 和 接口类型Intertype区别

  • type类型使用范围广,而接口类型只能用来声明对象
  • 在声明对象式,interface可以多次声明
  • type不可以不允许两个相同的名称的别名同时存在
  • interface可以多次声明一个接口名称
interface KKType1  {x: numbery: number
}
interface KKType1 {z: number
}
  • interface支持继承
// interface支持继承
interface KKPerson {name: stringage: number
}
interface ZZPerson extends KKPerson {height: number
}

1.5.ts类型断言

  • TypeScript无法获取具体的类型信息,这个我们需要使用类型断言
  • 断言只能断言成更加具体的类型,或者 不太具体(any/unknown) 类型
const img = document.querySelector(".img") as HTMLImageElement
img.src = "x"
img.alt = "y"

1.6.ts非空类型断言

  • 非空断言使用的是 ! ,表示可以确定某个标识符是有值的,跳过ts在编译阶段对它的检测
const info: KKPerson = {name: "kk",age: 18
}
console.log(info.lover?.name)// 类型缩小
if (info.lover) {info.lover.name = "zz"
}
// // 非空类型断言,但是只有确保lover一定有值的情况。才能使用

1.7.ts中字面量类型

const name: "kk" = "kk"
let age: 18 = 18

1.8.ts类型缩小


在给定的执行路径中,我们可以缩小比声明时更小的类型,这个过程称之为 缩小

  • typeof
function point(id: number | string) {if (typeof id === "string") {console.log(id.length, id.split(" "))} else {console.log(id)}
}
  • === / !==
type Direction = "left" | "right" | "up" | "down"
function turnDir(direction: Direction) {if (direction === "left") {console.log("left")} else if (direction === "right") {console.log("right")}
}
  • instanceof
    检查一个值是否是另一个值的“实例”
function printDate(date: string | Date) {if (date instanceof Date) {console.log(date.getTime())} else {console.log(date)}
}
  • in:判断是否有一个属性
interface KSing {sing: () => void
}interface KCoding {code: () => void
}
function lover(love: KSing | KCoding) {if ("sing" in love) {love.sing()} else if ("code" in love) {love.code()}
}
const KK: KSing = {sing: function() {}
}
const ZZ: KCoding = {code: function() {}
}
lover(KK)
lover(ZZ)