学习TS-day2-TypeScript语法细节(一)

51 阅读1分钟

一、类型别名的使用

1、type

type MyNumber = number
const age: MyNumber = 21
type IDType = number | string
function printID(id: IDType) {
    console.log(id)
}

2、interface

interface PointType {
    x: number
    y: number
    z?: number
}
function printCoordinate(point: PointType) {}

type和interface在使用上没有区别,type类型更广,interface只能定义对象,且可以声明多次、可以继承

interface PointType {
    x: number
    y: number
}

interface PointType {
    z: number
}
interface IPerson {
    name: string
    age: number
}

interface IKun extends Iperson {
    kouhao: string
}

const ikun1: IKun = {
    kouhao: "哎哟,你干嘛",
    name: "me",
    age: 21
}

二、类型断言

在确定类型的时候用类型断言,不用类型缩小

const imgEl = document.querySelector(".img") as HTMLImageElement
imgEl.src = "xxx"
imgEl.alt = "yyy"

不推荐使用非空类型断言

三、字面量类型

1、字面量类型的基本使用

const name: "MyName" = "me"
let age 21 = 21

2、将多个字面量类型联合起来

type Direction = "left" | "right" | "up" | "down"
const d1: Direction = "left"

四、类型缩小

1、typeof

function printID(id: number | string) {
    if (typeof id === "string") {
        console.log(id.length)
    } else {
        console.log(id)
    }
}

2、传入一个日期,打印日期

function printDate(date: string | Date) {
    if (date instanceof Date) {
        console.log(date.getTime())
    } else {
        console.log(date)
    }
}

3、in

interface ISwim {
    swim: () => void
}

interface IRum {
    run: () => void
}

function move(animal: ISwim | IRun) {
    if ("swim" in animal) {
        animal.swim()
    } else if ("run" in animal) {
        animal.run()
    }
}

五、函数类型

1、函数类型表达式

type BarType = (num: number) => number

const bar: BarType = (arg: number): number => {
    return 123
}

2、函数的调用签名

interface IBar {
    name: string
    age: number
    (num1: number): number
}

const bar: IBar = (num: number): number => {
    return 123
}

bar.name = "abc"
bar.age = 21
bar(123)