fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[TypeScript] 你有用过哪些ts的高级类型?

Open haizhilin2013 opened this issue 5 years ago • 1 comments
trafficstars

你有用过哪些ts的高级类型?

作者:rottenpen

3+1官网

我也要出题

haizhilin2013 avatar Jun 05 '20 00:06 haizhilin2013

TS 有哪些高级类型呢

在 TypeScript 中,高级类型提供了更强大的类型表达能力,帮助开发者定义更复杂和灵活的类型。以下是一些常见的 TypeScript 高级类型及其使用场景:

1. 交叉类型(Intersection Types)

交叉类型用于将多个类型合并为一个类型,它包含了所有合并类型的所有属性。

interface Person {
    name: string;
}

interface Employee {
    employeeId: number;
}

type EmployeePerson = Person & Employee;

let emp: EmployeePerson = {
    name: "John",
    employeeId: 123
};

2. 联合类型(Union Types)

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

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

printId(101);
printId("202");

3. 类型别名(Type Aliases)

类型别名用来为类型创建新的名称,尤其在联合类型或交叉类型中非常有用。

type Point = {
    x: number;
    y: number;
};

let p: Point = { x: 10, y: 20 };

4. 映射类型(Mapped Types)

映射类型允许你基于旧类型创建新类型,常用于对类型的属性进行批量操作。

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

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

type ReadOnlyPerson = ReadOnly<Person>;

let p: ReadOnlyPerson = { name: "John", age: 30 };
// p.name = "Doe"; // 错误: ReadOnlyPerson的属性是只读的

5. 条件类型(Conditional Types)

条件类型基于条件返回不同的类型。

type Message<T> = T extends string ? string : number;

let msg: Message<string> = "Hello";
let num: Message<number> = 42;

6. 索引类型(Index Types)

索引类型用于动态地访问类型的属性。

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

type PersonKeys = keyof Person; // "name" | "age"

function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}

let person: Person = { name: "John", age: 30 };
let personName = getProperty(person, "name"); // "John"

7. 元组类型(Tuple Types)

元组类型表示一个已知元素数量和类型的数组,各元素的类型不必相同。

let tuple: [string, number, boolean] = ["hello", 10, true];

8. 内置工具类型

TypeScript 提供了一些常用的内置工具类型,例如 Partial<T>Required<T>Readonly<T>Pick<T, K>Omit<T, K> 等。

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

type PartialPerson = Partial<Person>;
type RequiredPerson = Required<Person>;
type ReadonlyPerson = Readonly<Person>;
type PickPerson = Pick<Person, "name" | "age">;
type OmitPerson = Omit<Person, "address">;

let partialPerson: PartialPerson = { name: "John" };
let requiredPerson: RequiredPerson = { name: "John", age: 30, address: "123 St" };
let readonlyPerson: ReadonlyPerson = { name: "John", age: 30, address: "123 St" };
let pickPerson: PickPerson = { name: "John", age: 30 };
let omitPerson: OmitPerson = { name: "John", age: 30 };

9. 泛型(Generics)

泛型允许你定义在多个类型之间具有相同逻辑的组件。它们使得函数、类和接口更加通用和灵活。

function identity<T>(arg: T): T {
    return arg;
}

let output1 = identity<string>("myString");
let output2 = identity<number>(123);

10. 可辨识联合(Discriminated Unions)

可辨识联合是一种模式,它结合了联合类型和字面量类型的特性,用于类型安全的处理不同的值。

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

interface Circle {
    kind: "circle";
    radius: number;
}

type Shape = Square | Rectangle | Circle;

function area(shape: Shape): number {
    switch (shape.kind) {
        case "square":
            return shape.size * shape.size;
        case "rectangle":
            return shape.width * shape.height;
        case "circle":
            return Math.PI * shape.radius * shape.radius;
    }
}

let myShape: Shape = { kind: "circle", radius: 10 };
console.log(area(myShape)); // 314.159...

这些高级类型使得 TypeScript 非常强大和灵活,能够处理各种复杂的类型检查需求,提高代码的健壮性和可维护性。

llccing avatar Jun 28 '24 08:06 llccing