ts语法(四)

85 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

联合类型

TypeScript的类型系统允许我们使用多种运算符,从现有类型中构建新类型。

联合类型是由两个或者多个其他类型组成的类型;表示可以是这些类型中的任何一个值;联合类型中的每一个类型被称之为联合成员(union's members);

function fn(id: number | string) {
    console.log("id", id);
    //由于传入的id可能是string或者number,我们就不能对其调用string上的一些方法;
    if (typeof id === "string") {
        console.log("id为string类型", id.toLowerCase())
    } else {
        console.log("id为number类型", id);
    }
}
//满足其中一种类型即可
fn(123);
fn("abc")

可选类型

function fn(id?: string) {
    console.log("id", id);
}

fn();
fn("abc");
fn(undefined);

fn(null);// 报错

类型别名

类型别名顾名思义就是给一个类型起了个新别名, 当我们想要多次在其他地方使用该类型时,就不需要编写多次。例如:

  • 对象类型:
type Point = {
    lng: number, 
    lat: number
}

function fn(p: Point) {//直接使用Point
    console.log("经度", p.lng);
    console.log("纬度", p.lat);
}

fn({lng: 120, lat: 30})
  • 联合类型:
type ID = nember | string;
function fn(id: ID) {
    console.log("id", id);
}
fn(123);
fn("123");
fn(true); // 报错

类型断言as

有时候TypeScript无法获取具体的类型信息,这个我们需要使用类型断言(Type Assertions)

const imgDom = document.getElementById("logo-img");
//通过 document.getElementById,TypeScript只知道该函数会返回 HTMLElement ,但并不知道它具体的类型,所以获取不到src
console.log(imgDom.src); // 报错

//使用类型断言
const imgDom = document.getElementById("logo-img") as HTMLImageElement;
console.log(imgDom.src);

非空类型断言!

function fn(id?: string) {
    // 因为传入的id有可能为undefined,这时候不能执行方法
    console.log("id", id.toLowerCase()); // 报错
}

这时候我们可以使用非空类型断言,非空断言使用的是 ! ,表示可以确定某个标识符是有值的,跳过ts在编译阶段对它的检测

function fn(id?: string) {
    console.log("id", id!.toLowerCase()); 
}