- 使用聯(lián)合類型
聯(lián)合類型保證傳入的是聯(lián)合中的某一個類型的值即可
function setId(id: number | string) {
console.log(typeof id);
}
-可選類型補充
可選類型可以看作是 類型 和 undefined 的聯(lián)合類型:
function print(message?: string) {
console.log(message);
}
print();
print("message");
print(undefined);
-類型別名
針對對象,可以給對象類型起一個別名:
type Info = {
name: string,
age: number,
address: string
}
function printInfo(info: Info) {
console.log(info.name, info.age, info.address);
}
-類型斷言as
有的時候ts無法獲取到具體的類型信息,這時候需要我們?nèi)ナ褂妙愋蛿嘌?as)
常見的應(yīng)用場景:獲取document的元素
const myEl = document.getElementById('img') as HTMLImageElement
myEl.src = '.....'
ts只允許斷言轉(zhuǎn)換為更具體或者不是很具體的類型版本,主要用于防止不可能的強制轉(zhuǎn)換。
const data = 10 as string; // error
const data = (10 as unknown) as string;
-非空類型斷言
某個方法傳入的message可能存在undefined的時候,因此,這時候是會報錯的。
function print(message?: string) {
console.log(message.toUpperCase());
}
print("test");
非空斷言使用的是!,表示可以確定某個標(biāo)識符是有值的,可以跳過ts在編譯階段對它的監(jiān)測。
function print(message?: string) {
console.log(message!.toUpperCase());
}
-可選鏈的使用
當(dāng)對象的屬性不存在時,會短路,直接返回undefined,如果存在,便會繼續(xù)執(zhí)行。
type ParentInfo = {
name: string,
sonInfo?: {
name: string,
age?: number
}
}
const info: ParentInfo = {
name: "test1",
sonInfo: {
name: "test2",
age: 20
}
}
console.log(info.sonInfo?.name);
-??和!!的作用
!!操作符:
將一個其他類型轉(zhuǎn)換為boolean類型;
??操作符:
空值合并操作符(??)是一個邏輯操作符,當(dāng)操作符的左側(cè)是null或者undefined時,返回其右側(cè)操作符,否則返回左側(cè)操作符。
const message = " ";
let flag1 = Boolean(message);
let flag2 = !!message;
const message = 'message';
const result = message ?? 'test';
console.log(result);
-字面量類型
可以將多個類型聯(lián)合在一起
type Alignment = 'left' | 'right' | 'center';
function changeAlign(align: Alignment) {
console.log(align);
}
changeAlign('left');
-字面量推理

image.png
在進行字面量推理的過程中,info的參數(shù)實際上就是一個{label: string, send: string}的過程,因此,我們無法將string賦值到函數(shù)行參的字面量上去。
1、解決方法
const info = {
label: 'test',
send: 'B'
} as const
function getInfo(label: string, send: 'A' | 'B') {
console.log(label, send);
}
getInfo(info.label, info.send);
const info = {
label: 'test',
send: 'B'
}
function getInfo(label: string, send: 'A' | 'B') {
console.log(label, send);
}
getInfo(info.label, info.send as 'B');