Typescript
为了说明静态类型化的好处,由于环境变量中的错字,我仅花了 30 分钟进行调试 - TJ https://mobile.twitter.com/tjholowaychuk/status/1276470952059113473
vim 快速 fix,默认根据使用推测(即使推测不准,也省去一些书写)
基础类型 · TypeScript 中文网 · TypeScript——JavaScript 的超集
用 TypeScript 编写 React 的最佳实践-技术圈
Tuple 元组 有组织的数组
08 Record & Dictionary & Many G
Adopting Typescript at Scale - Brie Bunge | JSConf Hawaii 2019 - YouTube
ts-migrate/packages/ts-migrate at master · airbnb/ts-migrate
TS的ROI(投入回报率)是勾型的。小型且不长久的项目慎入,越是需要多人合作和生命周期越长的项目,回报率越高
interface 和 type
- 过去区别大,现在区别很小,都可以扩展
- interface 开放,可以覆盖,type 封闭,不能多次声明
- interface 适合开发库,便于扩展,写业务组件建议用 type
https://www.typescriptlang.org/play#example/types-vs-interfaces
interface Props {
name: string;
color: string;
}
type OtherProps = {
name: string,
color: string
}
对象入参
function Heading({ name, color }: Props): React.ReactNode {
return <h1>My Website Heading</h1>
}
extends
type 也可以扩展,用&
符号
type A = {
a: number
}
interface AB extends A {
b: string;
}
// 与上一种等价
type TAB = A & {
b: string
}
泛型
适用多个类型,保证返回类型一致
// 定义,相当于函数,入参是类型约束
function identity<T>(arg: T): T {
return arg
}
// 使用
let output = identity < string > 'myString' // type of output will be 'string'
React.FC 有泛型接口
type $TSFixMe = any
// @ts-nocheck
// @ts-ignore
// 没有错误后,会提示移除注释,优于 @ts-ignore
// @ts-expect-error
// tsx
{/*
// @ts-ignore */}
渐近nocheck -> expect-error
case
JSX element type 'Element[]' is not a constructor function for JSX elements #33487
React Element 要求是对象,用 Fragment 包下
TS2322: Type 'Timeout' is not assignable to type 'number'” when running unit tests
使用 windows.setTimeout 解决
No index signature with a parameter of type 'string' was found on type 'xxx'
对象访问下角标限制
Object is possibly 'undefined'?
提示结尾的访问,可能取不到,需要使用
?
新特性
unknown type 处理第三方库或 API 数据,表示需要检查数据有效性。如,接口字段有多种类型,null/[]
readonly scores: readonly number[];
第一个表示不能熏赋值,第二个表示内部不可变
const assertions 不可变数据结构
6 useful TypeScript 3 features you need to know | Building SPAs
getter 和 setter 作用
- 实现只读私有变量,不提供 setter
- 条件返回
- 钩子,自定义逻辑
- 参数校验
- 便于 TS 推导
private 是 ts 关键字
class Animal {
private _name = 'ppp'
get name() {
return this._name
}
set name(val: string) {
this._name = val
}
}
let pig = new Animal()
pig.name
pig.name = 'jack'
子组件需要的参数声明也不具有强制性,参考 React 组件参数传递是具有强约束力并且能静态检测,目前 Vue 仍然是在运行时抛出