线上ast解析浏览工具:https://ts-ast-viewer.com/
其实去看官方文档就够了,但是还是会把自己开发过程中,一些经常用到的,容易忘记的tip记下来,杂记
1.keyOf
2.ts-node
ts-node则包装了node,它可以直接的运行ts代码,其实就是用一个tsc(TypeScript compiler),把ts代码编译为js执行。
3.infer的用法
https://jkchao.github.io/typescript-book-chinese/tips/infer.html#%E4%BB%8B%E7%BB%8D
// infer 的作用当成 “提取类型中的子类型” 后就特别容易理解 type Obj<T> = T extends {a: infer VType, b: infer VType} ? VType : number; let obj1: Obj<string>; // number let obj2: Obj<true>; // number let obj3: Obj<{a: number, b: number}>; // number let obj4: Obj<{a: number, b: () => void}>; // number | (() => void) type Func<T> = T extends () => infer R ? R : boolean; let func1: Func<number>; // => boolean let func2: Func<''>; // => boolean let func3: Func<() => Promise<number>>; // => Promise<number>
4. 声明任意类型
4.1 obj: Record<string, any>
4.2 obj: {[key: string]: any}
5.2307的ts问题
Cannot find module '@/src/XXXX.vue'.ts(2307)
解决办法: https://github.com/vuejs/vue-cli/issues/1198
全局新建文件声明一下vue的类型
declare module '*.vue' { import Vue from 'vue'; export default Vue; }
该文件中不能存在import,一旦加了import,就会变成文件作用域, declare module '*.vue' 只会在该文件内生效。不加 import 就会在全局生效。
6.要改掉的10个ts坏习惯
https://mp.weixin.qq.com/s/rXs4Ok5LunVawJ8ZS3AUcw
- 比如用unknown替换any类型
- 拆解类型,不要让类型里面有太多可选属性
- 活用类型保护机制 type guard:https://www.tslang.cn/docs/handbook/advanced-types.html,加了类型保护,编译时就可以发现错误,不然只有运行时才能抛出错误
7. ts实用类型
https://www.typescriptlang.org/docs/handbook/utility-types.html#thisparametertypetype
有用的泛型:
- Partial<Type>
- Required<Type>
- Readonly<Type>
- Record<Keys,Type>
- Pick<Type, Keys>
- Omit<Type, Keys>
- Exclude<Type, ExcludedUnion>
- Extract<Type, Union>
- NonNullable<Type>
- Parameters<Type>
- ConstructorParameters<Type>
- ReturnType<Type>
- InstanceType<Type>
- ThisParameterType<Type>
- OmitThisParameter<Type>
- ThisType<Type>
- Intrinsic String Manipulation Types
- Uppercase<StringType>
- Lowercase<StringType>
- Capitalize<StringType>
- Uncapitalize<StringType>
8.ts类型中的逆变协变
https://mp.weixin.qq.com/s/fqlwqENlatj_u9aRctP41Q
子类型变量是可以赋值给父类型变量的虽然赋值成功,但是animal变量并没有.miao这个属性,说明发生了隐式转换。
9.as const
将引动类型的 const 变量转换为 readonly 类型;