TypeScript-映射类型(Mapped Types)

+-readonly/?

类型中的属性可以有readonly或者是?修饰,分别影响可变性和可选性。
如下:

type Account = {
    readonly id: number;
    name: string;
    age?: number;
    city?: string;
}

可以通过-readonly去掉Account类型中的readonly,造出一个新的类型。

type CreateMutable<T> = {
    -readonly [Property in keyof T]: T[Property]
}
type MutableAccount = CreateMutable<Account>;
type CreateMutable<T> = {
    -readonly [Property in keyof T]: T[Property]
}
type MutableAccount = CreateMutable<Account>;
/**
 * type MutableAccount = {
    id: number;
    name: string;
    age?: number | undefined;
    city?: string | undefined;
}
 */

如果不加-号,默认是+号,+ 的作用和-相反,可以给没有readonly的属性加上readonly

?的添加与删除与readonly类似:

type Concrete<T> = {
    [Property in keyof T]-?: T[Property];
}
type ConcreteAccount = Concrete<Account>;
/**
 * type ConcreteAccount = {
    readonly id: number;
    name: string;
    age: number;
    city: string;
}
 */

as关键字在此处的应用

type Getters<Type> = {
    -readonly [Property in keyof Type as `get${Capitalize<string & Property>}`]-?: () => Type[Property]
};
type GetAccount = Getters<Account>;
/**
 * type GetAccount = {
    getId: () => number;
    getName: () => string;
    getAge: () => number | undefined;
    getCity: () => string | undefined;
}
 */
type RmCityField<Type> = {
    -readonly [Property in keyof Type as Exclude<Property,"city">]-?: Type[Property]
};
type GetAccount = RmCityField<Account>;
/**
 * type GetAccount = {
    id: number;
    name: string;
    age: number;
}
 */
posted @ 2022-12-30 18:38  桃猫vi  阅读(102)  评论(0)    收藏  举报