TS高级操作 协变 逆变 双变 ts中的this和普通this区别

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代码
ts重载和重写区别
重载会改变参数列表,重写不会
重载会改变返回类型,重写不会
重载参数个数或者类型不同
重写参数个数,类型必须完全相同

 

转换工具
TypeStat   类不好
TypeWiz
Dts-gen
js-to-ts-converter  类转换的比较好
TS-migrate
fe-code
api-extractor
quickType

 

协变:
协变表示一个类型参数的子类型可以替代父类型
逆变:
逆变表示一个类型参数的父类型可以替代子类型
双变:
双变表示类型参数即可是协变的,也可以是逆变的

TypeScript 允许你在函数参数中显式指定 this 的类型,这有助于提高类型安全性。
TypeScript 中的 this 主要增加了对类型的支持,使得在编译时能够更好地捕获一些潜在的 this 错误,提高了代码的类型安全性。

 

posted @ 2021-12-16 10:24  国服第一李师师  阅读(293)  评论(0编辑  收藏  举报