首页 > 其他分享 >TypeScript readonly props All In One

TypeScript readonly props All In One

时间:2023-01-26 21:12:08浏览次数:40  
标签:www TypeScript age number readonly boolean props type

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,
}

(

标签:www,TypeScript,age,number,readonly,boolean,props,type
From: https://www.cnblogs.com/xgqfrms/p/17068207.html

相关文章

  • 【个人笔记】2023年搭建基于webpack5与typescript的react项目
    写在前面由于我在另外的一些文章所讨论或分析的内容可能基于一个已经初始化好的项目,为了避免每一个文章都重复的描述如何搭建项目,我在本文会统一记录下来,今后相关的文章直......
  • TypeScript reuse object's props All In One
    TypeScriptreuseobject'spropsAllInOneexport{};constlog=console.log;//typeCSSProps={[prop:string]:CSSProps};//typeCSSProps=CSSProps[]......
  • TypeScript Generic & Arrow Function All In One
    TypeScriptGeneric&ArrowFunctionAllInOne(......
  • 关于typescript异构枚举实现解析
    这里有几种实现方式:第一种是:A,B的实现Enum[Enum["A"]=0]="A";x=Enum["A"]=0;//x的值为0也就是说:Enum有两个键值:一个是0,他的值是“A”;一个是“A”,他的值是0;Enum......
  • typescript联合类型的类型缩减使用
    never是所有类型的子类型当我们想要一个这样一个类型时困难1因为采用索引签名要满足所有成员都必须符合字符串的索引签名所有不能采用{[index:string]:string|ag......
  • [Typescript 4.9] TypeScript 4.9: satisfies operator
    Previously,wehaveproblemforsuchcode:typeRGB=readonly[red:number,green:number,blue:number];typeColor={value:RGB|string};constmyColor......
  • vue3_ts_defineProps的使用
    一、defineProps在js中的使用//jssetupconstprops=defineProps({name:{type:String,default:'张三',//设置默认值......
  • 【TypeScript】学习笔记
    一.环境搭建安装Node.jsnpmi-gtypescript创建ts文件test.ts,编译:tsctest.ts二.基本类型1.类型声明语法:let变量:类型;let变量:类型=值;functionfn(参数:类型,参数:......
  • typescript中特殊符号(?/!)用法
    1.属性或参数中使用 ?:表示该属性或参数为可选项2. 属性或参数中使用 !:表示强制解析(告诉typescript编译器,这里一定有值),常用于vue-decorator中的@Prop3.变量后使用 !:表......
  • typescript封装LocalStorage并支持过期时间
    思考在我们使用​​cookie​​​的时候是可以设置有效期的,但是​​localStorage​​​本身是没有该机制的,只能人为的手动删除,否则会一直存放在浏览器当中,可不可以跟cookie一......