大量摘抄于各种文章 ———— 站在巨人的肩膀上搬砖
TypeScript官方文档
(中文版)
是最好的学习材料html
TypeScript = Type + Script(标准JS)。咱们从TS的官方网站上就能看到定义:TypeScript is a typed superset of JavaScript that compiles to plain JavaScript。TypeScript是一个编译到纯JS的有类型定义的JS超集。react
如何更好的利用JS的动态性和TS的静态特质,咱们须要结合项目的实际状况来进行综合判断。一些建议:webpack
至于到底用不用TS,仍是要看实际项目规模、项目生命周期、团队规模、团队成员状况等实际状况综合考虑。git
低级错误、非空判断、类型推断,这类问题是ESLint等工具检测不出来的。
let isDone: boolean = false; let decimal: number = 6; let color: string = "blue"; // 数组,有两种写法 let list: number[] = [1, 2, 3]; let list: Array<number> = [1, 2, 3]; // 元组(Tuple) let x: [string, number] = ["hello", 10]; // 枚举 enum Color {Red = 1, Green = 2, Blue = 4} let c: Color = Color.Green; // 不肯定的能够先声明为any let notSure: any = 4; // 声明没有返回值 function warnUser(): void { alert("This is my warning message"); } let u: undefined = undefined; let n: null = null; // 类型永远没返回 function error(message: string): never { throw new Error(message); } // 类型主张,就是知道的比编译器多,主动告诉编译器更多信息,有两种写法 let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; let strLength: number = (someValue as string).length;
信息隐藏有助于更好的管理系统的复杂度,这在软件工程中显得尤其重要。github
class Person { protected name: string; public age: number; constructor(name: string) { this.name = name; } } class Employee extends Person { static someAttr = 1; private department: string; constructor(name: string, department: string) { super(name); this.department = department; } } let howard = new Employee("Howard", "Sales"); console.log(howard.name); // 报错:Person中name属性是protected类型,只能在本身类中或者子类中使用
Robot类能够继承Base类,并实现Machine和Human接口,
这种能够组合继承类和实现接口的方式使面向对象编程更为灵活、可扩展性更好。web
interface Machine { move(): void } interface Human { run(): void } class Base { } class Robot extends Base implements Machine, Human { run() { console.log('run'); } move() { console.log('move'); } }
定义了一个模板类型T,实例化GenericNumber类时能够传入内置类型或者自定义类型。泛型(模板)在传统面向对象编程语言中是很常见的概念了,在代码逻辑是通用模式化的,参数能够是动态类型的场景下比较有用。typescript
class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T; } let myGenericNumber = new GenericNumber<number>(); myGenericNumber.zeroValue = 0; myGenericNumber.add = function(x, y) { return x + y; };
定义了一个系统配置类型SystemConfig和一个模块类型ModuleType,咱们在使用这些类型时就不能随便修改config和mod的数据了,这对于多人协做的团队项目很是有帮助。npm
interface SystemConfig { attr1: number; attr2: string; func1(): string; } interface ModuleType { data: { attr1?: string, attr2?: number }, visible: boolean } const config: SystemConfig = { attr1: 1, attr2: 'str', func1: () => '' }; const mod: ModuleType = { data: { attr1: '1' }, visible: true };
TS除了支持ES6的模块系统以外,还支持命名空间。这在管理复杂模块的内部时比较有用。编程
namespace N { export namespace NN { export function a() { console.log('N.a'); } } } N.NN.a();
面向对象相关概念详见json
对于老项目,因为TS兼容ES规范,因此能够比较方便的升级现有的JS(这里指ES6及以上)代码,逐渐的加类型注解,渐进式加强代码健壮性。迁移过程:
"target":"es5"
:编译后代码的ES版本,还有es3,es2105等选项。"module":"commonjs"
:编译后代码的模块化组织方式,还有amd,umd,es2015等选项。"strict":true
:严格校验,包含不能有没意义的any,null校验等选项。tsconfig.json
无需修改,增长"allowJs": true
选项。loaders: [ // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. { test: /\.tsx?$/, loader: "awesome-typescript-loader" } ]
对于新项目,微软提供了很是棒的一些Starter项目,详细介绍了如何用TS和其余框架、库配合使用。若是是React项目,能够参考这个Starter:TypeScript-React-Starter
React、及其余各类著名框架、库都有TS类型声明,咱们能够在项目中经过npm install @types/react方式安装,能够在这个网站搜索你想要安装的库声明包。安装后,写和那些框架、库相关的代码将会是一种很是爽的体验,函数的定义和注释将会自动提示出来,开发效率将会获得提高。
type Name = string; type NameResolver = () => string; type NameOrResolver = Name | NameResolver; function getName(n: NameOrResolver): Name { if (typeof n === 'string') { return n; } else { return n(); } }
type Person = Huaren & Bairen & Heiren;
function getLength(something: string | number): number { return something.length;❌ } // index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'. // Property 'length' does not exist on type 'number'. function getString(something: string | number): string { return something.toString();✅ }
type EventNames = 'click' | 'scroll' | 'mousemove'; function handleEvent(ele: Element, event: EventNames) { // do something } handleEvent(document.getElementById('hello'), 'scroll'); // 没问题 handleEvent(document.getElementById('world'), 'dblclick'); // 报错,event 不能为 'dblclick' // index.ts(7,47): error TS2345: Argument of type '"dblclick"' is not assignable to parameter of type 'EventNames'.
interface Cat { name: string; run(): void; } interface Fish { name: string; swim(): void; } function isFish(animal: Cat | Fish) { if (typeof animal.swim === 'function'❌) { return true; } return false; } // index.ts:11:23 - error TS2339: Property 'swim' does not exist on type 'Cat | Fish'. // Property 'swim' does not exist on type 'Cat'. function isFish(animal: Cat | Fish) { if (typeof (animal as Fish✅).swim === 'function') { return true; } return false; }
类型谓词守卫自定义类型
function isFish(animal: Fish | Bird): animal is Fish { return (animal as Fish).swim !== undefined; }
typeof类型守卫
typeof v === "typename"
和typeof v !== "typename"
两种形式能被识别"number"
, "string"
, "boolean"
, "symbol"
instanceof类型守卫
instanceof
用于守护类function getRandomPadder() { return Math.random() < 0.5 ? new SpaceRepeatingPadder(4) : new StringPadder(" "); } // 类型为SpaceRepeatingPadder | StringPadder let padder: Padder = getRandomPadder(); if (padder instanceof SpaceRepeatingPadder) { padder; // 类型细化为'SpaceRepeatingPadder' } if (padder instanceof StringPadder) { padder; // 类型细化为'StringPadder' }
interface Lengthwise { length: number; } function loggingIdentity<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg; }
举个例子:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key] } interface IObj { name: string; age: number; male: boolean; } const obj:IObj = { name: 'zhangsan', age: 18, male: true } let x1 = getProperty(obj, 'name') // 容许,x1的类型为string let x2 = getProperty(obj, 'age') // 容许,x2的类型为number let x3 = getProperty(obj, 'male') // 容许,x3的类型为boolean let x4 = getProperty(obj, 'sex') // 报错:Argument of type '"sex"' is not // assignable to parameter of type '"name" | "age" | "male"'.
getProperty
函数,来获取指定对象的指定属性keyof
关键字,得到泛型T
上已知的公共属性名联合的字符串字面量类型'name' | 'age' | 'male'
K extends keyof T
限制K
只能是'name' | 'age' | 'male'
中的一个值T[K]
则表明对象里对应key的元素的类型更好的理解索引类型
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] { return names.map(n => o[n]); } // T[K][]也能够写成 Array<T[K]> interface Person { name: string; age: number; sex: string; } let person: Person = { name: 'Jarid', age: 35, sex: '男', }; let strings: string[] = pluck(person, ['name', 'sex']); // ok, string[], [ 'Jarid', '男' ] let numbers: number[] = pluck(person, ['age']); // ok, number[], [ 35 ] let persons: (string | number)[] = pluck(person, ['name', 'sex', 'age']); // [ 'Jarid', '男', 35 ]
type
`keyof咱们就能够获取跟随
interface Person`变化的字符串字面量类型interface Person { name: string; age: number; location: string; } type K1 = keyof Person; // "name" | "age" | "location" type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ... type K3 = keyof { [x: string]: Person }; // string
interface Person { name: string; age: number; } type Partial<T> = { [P in keyof T]?: T[P]; } type PersonPartial = Partial<Person>; --------------------------------------- type Readonly<T> = { readonly [P in keyof T]: T[P]; } type ReadonlyPerson = Readonly<Person>; // 至关于 type ReadonlyPerson = { readonly name: string; readonly age: number; }
Omit<T, K> TypeScript 3.5 //让咱们能够从一个对象类型中剔除某些属性,并建立一个新的对象类型 Partial<T>,TypeScript 2.1 // 将构造类型T全部的属性设置为可选的 Readonly<T>,TypeScript 2.1 // 将构造类型T全部的属性设置为只读的 Record<K,T>,TypeScript 2.1 // 可用来将某个类型的属性映射到另外一个类型上 Pick<T,K>,TypeScript 2.1 // 从类型T中挑选部分属性K来构造类型 Exclude<T,U>,TypeScript 2.8 // 从类型T中剔除全部能够赋值给U的属性,而后构造一个类型 Extract<T,U>,TypeScript 2.8 // 从类型T中提取全部能够赋值给U的类型,而后构造一个类型 NonNullable<T>,TypeScript 2.8 // 从类型T中剔除null和undefined,而后构造一个类型 ReturnType<T>,TypeScript 2.8 // 由函数类型T的返回值类型构造一个类型 InstanceType<T>,TypeScript 2.8 // 由构造函数类型T的实例类型构造一个类型 Required<T>,TypeScript 2.8 // 构造一个类型,使类型T的全部属性为required必选 ThisType<T>,TypeScript 2.8 // 这个工具不会返回一个转换后的类型。它作为上下文的this类型的一个标记。注意,若想使用此类型,必须启用--noImplicitThis
jsx
语法的文件都须要以tsx
后缀命名Component<P, S>
泛型参数声明,来代替PropTypes
!window
对象属性,统一在项目根下的global.d.ts
中进行声明定义types/
目录下定义好其结构化类型声明class App extends Component<IProps, IState> { static defaultProps = { // ... } readonly state = { // ... }; // 小技巧:若是state很复杂不想一个个都初始化, // 能够结合类型断言初始化state为空对象或者只包含少数必须的值的对象: // readonly state = {} as IState; }
须要特别强调的是,若是用到了state
,除了在声明组件时经过泛型参数传递其state
结构,还须要在初始化state
时声明为 readonly
这是由于咱们使用 class properties 语法对state作初始化时,会覆盖掉Component<P, S>
中对state
的readonly
标识。
// SFC: stateless function components // v16.7起,因为hooks的加入,函数式组件也可使用state,因此这个命名不许确。 // 新的react声明文件里,也定义了React.FC类型 const List: React.SFC<IProps> = props => null
// 能够推断 age 是 number类型 const [age, setAge] = useState(20); // 初始化值为 null 或者 undefined时,须要显示指定 name 的类型 const [name, setName] = useState<string>(); // 初始化值为一个对象时 interface People { name: string; age: number; country?: string; } const [owner, setOwner] = useState<People>({name: 'rrd_fe', age: 5}); // 初始化值是一个数组时 const [members, setMembers] = useState<People[]([]);
// bad one class App extends Component { state = { a: 1, b: 2 } componentDidMount() { this.state.a // ok: 1 // 假如经过setState设置并不存在的c,TS没法检查到。 this.setState({ c: 3 }); this.setState(true); // ??? } // ... } // React Component class Component<P, S> { constructor(props: Readonly<P>); setState<K extends keyof S>( state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null), callback?: () => void ): void; forceUpdate(callBack?: () => void): void; render(): ReactNode; readonly props: Readonly<{ children?: ReactNode }> & Readonly<P>; state: Readonly<S>; context: any; refs: { [key: string]: ReactInstance }; } // interface IState{ // a: number, // b: number // } // good one class App extends Component<{}, { a: number, b: number }> { readonly state = { a: 1, b: 2 } //readonly state = {} as IState,断言所有为一个值 componentDidMount() { this.state.a // ok: 1 //正确的使用了 ts 泛型指示了 state 之后就会有正确的提示 // error: '{ c: number }' is not assignable to parameter of type '{ a: number, b: number }' this.setState({ c: 3 }); } // ... }
什么是 react 高阶组件? 装饰器?
第一,是否还能使用装饰器语法调用高阶组件?
import { RouteComponentProps } from 'react-router-dom'; const App = withRouter(class extends Component<RouteComponentProps> { // ... }); // 如下调用是ok的 <App />
如上例子,咱们在声明组件时,注解了组件的props是路由的RouteComponentProps结构类型,可是咱们在调用App组件时,并不须要告知RouteComponentProps里具备的location、history等值,这是由于withRouter这个函数自身对其作了正确的类型声明。
第二,使用装饰器语法或者没有函数类型签名的高阶组件怎么办?
就是将高阶组件注入的属性都声明可选(经过Partial这个映射类型),或者将其声明到额外的injected组件实例属性上。
import { RouteComponentProps } from 'react-router-dom'; // 方法一 @withRouter class App extends Component<Partial<RouteComponentProps>> { public componentDidMount() { // 这里就须要使用非空类型断言了 this.props.history!.push('/'); } // ... }); // 方法二 @withRouter class App extends Component<{}> { get injected() { return this.props as RouteComponentProps } public componentDidMount() { this.injected.history.push('/'); } // ...
interface IVisible { visible: boolean; } //排除 IVisible function withVisible<Self>(WrappedComponent: React.ComponentType<Self & IVisible>): React.ComponentType<Omit<Self, 'visible'>> { return class extends Component<Self> { render() { return <WrappedComponent {...this.props} visible={true} /> } } }
参考文章
TypeScript 入门教程
使用 TypeScript 装饰器装饰你的代码
优雅的在 react 中使用 TypeScript
TypeScript 中使用React Hook
TypeScript体系调研报告