interface Todo { title: string; description: string; completed: boolean; } interface Todo1 { completed:boolean; title:string; } type B = number | boolean type C = boolean | undefined type Select = 'title'|'description' type A1 = Pick<Todo,'title'|'completed'>//选取指定 type A2 = Partial<Todo> //变成可选 type A11 = Partial<Pick<Todo,Select>>//先Pick选取指定的,再变成可选 type A3 = Required<Todo>//变成必选 type A4 = Omit<Todo,'title'>//排除 type A5 = Exclude<B,C>//选出不一样的,排除掉交集 type A6 = Omit<Todo,Select> type A7 = A11 & A6 const s:A7 = { completed:true, title:'ii', description:'shi' } //部门可选,部分不可选 type SelectPartial<T,V extends keyof T> = Partial<Pick<T,V>> & Omit<T,V> // type Final = SelectPartial<Todo,Select> const code:Final = { completed:true, description:'bai' }
取值参考
const obj = { eth:100, bnb:'xxx' } res = number|string res是我想要取的东西 1. type res = typeof obj[keyof typeof obj] 2. type getValue<T> = { [P in keyof T]:T[P] }[keyof T] type res = getValue<typeof obj>
const item2 = [1021,'1839',null] res = number|string|null res是我想要的东西 type res = (typeof item2)[number]
const item = [1021,'1839'] as const res = 1021|'1839' res是我想要的东西,值作为类型 1. type fe<T> = T extends ReadonlyArray<infer R>?R:never type res = fe<typeof item> 2. type de<T extends ReadonlyArray<unknown> > = T extends ReadonlyArray<infer R>?R:never; type res = de<typeof item>
ts编译原理: https://github.com/microsoft/TypeScript/tree/main/src/compiler 1.scanner 扫描器 里面有一个scanner.ts ,扫描所有文件,找出哪些文件需要被编译,扫描过程类似node文件查找过程 2.parser 解析器 parser.ts 将文件内容生成抽象语法树,树的节点成为node 3.binder绑定器 binder.ts为有命名的实体node 生成对应的symbol 4.checker 检查器 checker.ts TypeChecker是typescript类型系统的核心,他为symbol生成相应的类型信息 5.emitter 发射器 输出文件可能是 .js .d.ts .js.map ts源码经过scanner扫描器扫描,生成token数据流,经过parser解析器生成ast语法树,经过binder绑定器为有命名实体的node生成对应的symbol 经过checker检查器,生成对应的类型信息,经过发射器,生成javascript代码