duuliy

ts巧用

2020-2-26

一.处理第三方库类型相关问题

a.安装 @types/webpack-env 引用相对应的ts类型
b.若没有就自己来 declare module “lodash”
c.Import 后通过 extends 或者 merge 能力对原类型进行扩展 或 忍受类型的丢失或不可靠性 或 使用 // @ts-ignore 忽略
d. 报错时:在 compilerOptions 的添加”skipLibCheck”: true, 曲线救国

二. 巧用类型收缩解决报错

1.类型断言
2.类型守卫 typeof in instanceof 字面量类型保护
3.双重断言 xx as any as string

三. 巧用 typescript 支持的 js 最新特性优化代码

js和ts实现不一样
1.let x = foo?.bar.baz();
2. 空值联合 let x = foo ?? ‘22’;

四. 巧用高级类型灵活处理数据
五. 辨别 type & interface

相同点:都可以描述一个对象或者函数
不同点:interface 可以 extends, type 是不允许 extends 和 implement 的,
但是 type 缺可以通过交叉类型 实现 interface 的 extend 行为,并且两者并不是相互独立的,也就是说 interface 可以 extends type, type 也可以 与 interface 类型 交叉 。