做者:Marius Schulz
译者:前端小智
来源: https://mariusschulz.com/
点赞再看,养成习惯本文
GitHub
https://github.com/qq44924588... 上已经收录,更多往期高赞文章的分类,也整理了不少个人文档,和教程资料。欢迎Star和完善,你们面试能够参照考点复习,但愿咱们一块儿有点东西。javascript
TypeScript 2.3 增长了对声明泛型参数默认类型的支持,容许为泛型类型中的类型参数指定默认类型。前端
接下来看看如何经过泛型参数默认将如下React
组件从 JS (和JSX)迁移到 TypeScript (和TSX):java
class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span>; } }
我们先从为 Component
类建立类型定义开始。每一个基于类的 React 组件都有两个属性: props
和 state
,类型定义结构大体以下:node
declare namespace React { class Component { props: any; state: any; } }
注意,这个是大大简化的示例,由于我们是为了演示泛型类型参数及其默认值的内容。react
如今就能够经过继承来调用上面定义的 Component
:git
class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span> } }
我们能够以下方式建立组件的实例:github
<Greeting name="world" />
渲染上面组件会生成如下 HTML:面试
<span>Hello, World!</span>
nice,继续。typescript
虽然上面的示例编译和运行得很好,可是我们的 Comp
onent 类型定义不是很精确。由于我们将 props
和 state
类型设置为 any
,因此 TypeScript 编译器也帮不上什么忙。express
我们得更具体一点,经过两种泛型类型: Props
和 State
,这样就能够准确地描述 props
和 state
属性的结构。
declare namespace React { class Component <Props, State> { props: Props; state: State; } }
接着建立一个GreetingProps
类型,该类型定义一个字符串类型 name
的属性,并将其做为Props
类型参数的类型参数传递:
type GreetingProps = { name: string }; class Greeting extends React.Component<GreetingProps, any> { render() { return <span>Hello, {this.props.name}!</span>; } }
1) GreetingProps
是类型参数Props
的类型参数
2) 相似地,any
是类型参数 State
的类型参数
有了这些类型,我们的组件获得更好的类型检查和自动提示:
可是,如今使用 React.Component
类时就必需供两种类型。我们开着的初始代码示例就不在正确地进行类型检查:
// Error: 泛型类型 Component<Props, State> // 须要 2 个类型参数。 class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span>; } }
若是我们不想指定像GreetingProps
这样的类型,能够经过为Props
和State
类型参数提供any
类型来修正代码:
class Greeting extends React.Component<any, any> { render() { return <span>Hello, {this.props.name}!</span>; } }
这种方法可让编译器经过,但我们还有更优雅的作法:泛型参数默认类型。
从 TypeScript 2.3 开始,我们能够为每一个泛型类型参数添加一个默认类型。在下面的例子中,若是没有显式地给出类型参数,那么 Props
和 State
都都是 any
类型:
declare namespace React { class Component<Props = any, State = any> { props: Props; state: State; } }
如今,我们就能够不用指定泛型类型就能够经过编译器的检查:
class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span>; } }
固然,我们仍然能够显式地为Props
类型参数提供类型并覆盖默认的any
类型,以下所示:
type GreetingProps = { name: string }; class Greeting extends React.Component<GreetingProps, any> { render() { return <span>Hello, {this.props.name}!</span>; } }
这两个类型参数如今都有一个默认类型,因此它们是可选的,我们能够仅为Props
指定显式的类型参数:
type GreetingProps = { name: string };
class Greeting extends React.Component<GreetingProps> { render() { return <span>Hello, {this.props.name}!</span>; } }
注意,我们只提供了一个类型参数。可是,被省略可选类型参数前一个必需要指定类型,不然不能省略。
在上一篇中关于 TypeScript 2.2 中混合类的文章中,我们最初声明了如下两个类型别名:
type Constructor<T> = new (...args: any[]) => T; type Constructable = Constructor<{}>;
Constructable
类型纯粹是语法糖。它能够代替 Constructor<{}>
类型,这样就没必要每次都要写泛型类型参数。使用泛型参数默认值,就能够彻底去掉附加的可构造类型,并将{}
设置为默认类型
type Constructor<T = {}> = new (...args: any[]) => T;
语法稍微复杂一些,可是生成的代码更简洁,Good。
--strict
主要编译选项TypeScript 2.3 引入了一个新的 --strict
编译器选项,它支持许多与更严格的类型检查相关的其余编译器选项。
TypeScript 加入的新检查项为了不不兼容现有项目一般都是默认关闭的。虽然避免不兼容是好事,但这个策略的一个弊端则是使配置最高类型安全愈来愈复杂,这么作每次 TypeScript 版本发布时都须要显示地加入新选项。有了--strict
编译选项,就能够选择最高级别的类型安全(了解随着更新版本的编译器增长了加强的类型检查特性可能会报新的错误)。
新的--strict
编译器选项包含了一些建议配置的类型检查选项。具体来讲,指定--strict
至关因而指定了如下全部选项(将来还可能包括更多选项):
将来的 TypeScript 版本可能会在这个集合中添加额外的类型检查选项。这意味着我们不须要监控每一个 TypeScript 版原本得到应该在项目中启用的新严格性选项。若是向上述选项集添加了新选项,则在升级项目的 TypeScript 版本后,它们将自动激活。
--strict
编译选项会为以上列出的编译器选项设置默认值。这意味着还能够单独控制这些选项。好比:
--strict --noImplicitThis false
或者在tsconfig.json
文件指定:
{ "strict": true, "alwaysStrict": false }
这将是开启除--noImplicitThis
编译选项之外的全部严格检查选项。使用这个方式能够表述除某些明确列出的项之外的全部严格检查项。换句话说,如今能够在默认最高级别的类型安全下排除部分检查。
--init
输出除了默认的--strict
设置外,tsc --init
还改进了输出。tsc --init
默认生成的tsconfig.json
文件如今包含了一些带描述的被注释掉的经常使用编译器选项. 你能够去掉相关选项的注释来得到指望的结果。咱们但愿新的输出能简化新项目的配置而且随着项目成长保持配置文件的可读性。
经过 tsc --init
编译器能够为构建一个配置文件:
$ tsc --init message TS6071: Successfully created a tsconfig.json file.
运行此命令后,会当前工做目录中生成一个tsconfig.json
文件,生成的配置以下所示:
{ "compilerOptions": { /* Basic Options */ "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */ // "lib": [], /* Specify library files to be included in the compilation: */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ // "outDir": "./", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true /* Enable all strict type-checking options. */ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ /* Source Map Options */ // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ } }
注意 --strict
是默认启用的。这意味着在启动一个新的TypeScript项目时,自动进入默认模式。
--checkJS
选项下 .js
文件中的错误即使使用了--allowJs
,TypeScript 编译器默认不会报 .js
文件中的任何错误。TypeScript 2.3 中使用--checkJs
选项,.js
文件中的类型检查错误也能够被报出.
你能够经过为它们添加// @ts-nocheck
注释来跳过对某些文件的检查,反过来你也能够选择经过添加// @ts-check
注释只检查一些.js
文件而不须要设置--checkJs
编译选项。你也能够经过添加// @ts-ignore
到特定行的一行前来忽略这一行的错误.
.js
文件仍然会被检查确保只有标准的 ECMAScript 特性,类型标注仅在.ts
文件中被容许,在.js
中会被标记为错误。JSDoc注释能够用来为你的 JS 代码添加某些类型信息,
代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug。
原文:
https://mariusschulz.com/blog...
https://mariusschulz.com/blog...
干货系列文章汇总以下,以为不错点个Star,欢迎 加群 互相学习。
https://github.com/qq44924588...
我是小智,公众号「大迁世界」做者,对前端技术保持学习爱好者。我会常常分享本身所学所看的干货,在进阶的路上,共勉!
关注公众号,后台回复福利,便可看到福利,你懂的。