TypeScript readonly props All In One
TS 绕过 readonly
限制
readonly properties
interface Person {
name: string;
age: number;
}
interface ReadonlyPerson {
readonly name: string;
readonly age: number;
}
let writablePerson: Person = {
name: "Person McPersonface",
age: 42,
};
// 绕过 readonly 限制 ✅
let readonlyPerson: ReadonlyPerson = writablePerson;
console.log(readonlyPerson.age);
// '42'
writablePerson.age++;
console.log(readonlyPerson.age);
// '43'
Mapped Types
// type ObjType = {
// [key: string]: boolean | number | boolean;
// };
// type OptionsFlags<ObjType> = {
// [Property in keyof ObjType]: boolean;
// };
type ObjType = {
k1: boolean;
k2: number;
k3: boolean;
};
type OptionsFlags<T> = {
[Property in keyof T]: boolean;
};
const test: OptionsFlags<ObjType> = {
k1: true,
k2: false,
// k3: 123,
// Type 'number' is not assignable to type 'boolean'.(2322)
k3: true,
}