TypeScript学习之路 - 高级类型

TypeScript 高级类型

TypeScript 提供了几种高级类型,使得类型系统更加灵活和表达力强大。让我们逐一探讨这些高级类型。

1. 交叉类型(Intersection Types)

交叉类型将多个类型合并为一个类型,包含了所需的所有类型的特性。

interface BusinessPartner {
    name: string;
    credit: number;
}

interface Identity {
    id: number;
    email: string;
}

type Employee = BusinessPartner & Identity;

let e: Employee = {
    name: "John Smith",
    credit: 10000,
    id: 100,
    email: "john@example.com"
};

在这个例子中,Employee 类型包含了 BusinessPartnerIdentity 的所有属性。

2. 联合类型(Union Types)

联合类型表示一个值可以是几种类型之一。

function printId(id: number | string) {
    console.log("Your ID is: " + id);
}

printId(101);  // 有效
printId("202");  // 有效
// printId({ myID: 22342 });  // 错误

3. 类型守卫(Type Guards)

类型守卫允许你缩小联合类型的范围。

function isNumber(x: any): x is number {
    return typeof x === "number";
}

function printAll(strs: string | string[] | null) {
    if (strs && typeof strs === "object") {
        for (const s of strs) {
            console.log(s);
        }
    } else if (typeof strs === "string") {
        console.log(strs);
    }
}

4. 可为 null 的类型

TypeScript 有两个特殊的类型,nullundefined,它们分别具有值 null 和 undefined。

let s: string | null = "bar";
s = null;  // 有效
// s = undefined;  // 错误,undefined 不能赋值给 'string | null'

5. 字面量类型(Literal Types)

字面量类型允许你指定一个值必须有一个确切的值。

type Easing = "ease-in" | "ease-out" | "ease-in-out";

function animate(dx: number, dy: number, easing: Easing) {
    // ...
}

animate(0, 0, "ease-in");
// animate(0, 0, "linear");  // 错误

6. 索引类型(Index Types)

索引类型允许你使用动态属性名。

function pluck<T, K extends keyof T>(o: T, propertyNames: K[]): T[K][] {
    return propertyNames.map(n => o[n]);
}

interface Car {
    manufacturer: string;
    model: string;
    year: number;
}

let taxi: Car = {
    manufacturer: 'Toyota',
    model: 'Camry',
    year: 2014
};

let makeAndModel: string[] = pluck(taxi, ['manufacturer', 'model']);

7. 映射类型(Mapped Types)

映射类型允许你从旧类型创建新类型。

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

type Partial<T> = {
    [P in keyof T]?: T[P];
};

interface Person {
    name: string;
    age: number;
}

type ReadonlyPerson = Readonly<Person>;

8. 条件类型(Conditional Types)

条件类型根据条件选择类型。

type TypeName<T> = 
    T extends string ? "string" :
    T extends number ? "number" :
    T extends boolean ? "boolean" :
    T extends undefined ? "undefined" :
    T extends Function ? "function" :
    "object";

type T0 = TypeName<string>;  // "string"
type T1 = TypeName<"a">;  // "string"
type T2 = TypeName<true>;  // "boolean"

这些高级类型特性使得 TypeScript 的类型系统非常强大,能够表达复杂的类型关系和约束。正确使用这些特性可以帮助你创建更安全、更易维护的代码。

赶紧学习会了他

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

跳房子的前端

你的打赏能让我更有力地创造

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值