TypeScript笔记 —— 类型断言

105 阅读2分钟

类型断言as

有时候TypeScript无法获取具体的类型信息,这个我们需要使用类型断言。比如我们通过 document.getElementById,TypeScript只知道该函数会返回 HTMLElement ,但并不知道它具体的类型。

const myEl = document.getElementById("my-img") as HTMLImageElement
myEl.src = "xxxx"

TypeScript只允许类型断言转换为 更具体 或者 不太具体 的类型版本,此规则可防止不可能的强制转换。

const name = 'haha' as number

image.png

const name = ("haha" as unknown) as number

非空类型断言!

当我们编写下面的代码时,在执行ts的编译阶段会报错。

function printMessage(message?: string) {
    console.log(message.toUpperCase())
}
printMessage("hello")

image.png 这是因为传入的message有可能是为undefined的,这个时候是不能执行方法的。但是,我们确定传入的参数是有值的,这个时候我们可以使用非空类型断言。非空断言使用的是 ! ,表示可以确定某个标识符是有值的,跳过ts在编译阶段对它的检测。

function printMessage(message?: string) {
    console.log(message!.toUpperCase())
}

字面量类型

除了前面我们所讲过的类型之外,也可以使用字面量类型。

let message: "Hello World" = "Hello World"
// Type '"haha"' is not assignable to type '"Hello World"'
message = "haha"

那么这样做有什么意义呢?默认情况下这么做是没有太大的意义的,但是我们可以将多个类型联合在一起。

type Alignment = 'left' | 'right' | 'center'
function changeAlign(align: Alignment) {
    console.log(align)
}
changeAlign('left')

字面量推理

我们来看下面的代码。

const info = {
    url: "https://coderwhy.org/abc",
    method: "GET"
}

function request(url: string, method: "GET" | "POST") {
    console.log(url, method)
}

request(info.url, info.method)

这是因为我们的对象在进行字面量推理的时候,info其实是一个 {url: string, method: string},所以我们没办法将一个 string赋值给一个 字面量 类型。

解决方法

request(info.url, info.method as "GET")
const info = {
    url: "https://coderwhy.org/abc",
    method: "GET"
} as const