+-
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;
}
*/
标签:TypeScript,string,number,readonly,keyof,Mapped,Property,type,Types
From: https://www.cnblogs.com/savannah047/p/17015638.html