TypeScript泛型參數(shù)默認類型和新的strict編譯選項
概述
TypeScript 2.3 增加了對聲明泛型參數(shù)默認類型的支持,允許為泛型類型中的類型參數(shù)指定默認類型。
接下來看看如何通過泛型參數(shù)默認將以下react組件從js(和jsX)遷移到 TypeScript (和TSX):
class Greeting extends react.Component { render() { return <span>Hello, {this.props.name}!</span>; } }
為組件類創(chuàng)建類型定義
咱們先從為Component類創(chuàng)建類型定義開始。每個基于類的 React 組件都有兩個屬性:props和state,類型定義結(jié)構(gòu)大致如下:
declare namespace React { class Component { props: any; state: any; } }
注意,這個是大大簡化的示例,因為咱們是為了演示泛型類型參數(shù)及其默認值的內(nèi)容。
現(xiàn)在就可以通過繼承來調(diào)用上面定義的Component:
class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span> } }
咱們可以如下方式創(chuàng)建組件的實例:
<Greeting name="world" />
渲染上面組件會生成以下html:
<span>Hello, World!</span>
nice,繼續(xù)。
使用泛型類型定義 Props 和 State
雖然上面的示例編譯和運行得很好,但是咱們的 Component 類型定義不是很精確。因為咱們將props和state類型設置為any,所以 TypeScript 編譯器也幫不上什么忙。
咱們得更具體一點,通過兩種泛型類型:Props和State,這樣就可以準確地描述props和state屬性的結(jié)構(gòu)。
declare namespace React { class Component <Props, State> { props: Props; state: State; } }
接著創(chuàng)建一個GreetingProps類型,該類型定義一個字符串類型name的屬性,并將其作為Props類型參數(shù)的類型參數(shù)傳遞:
type GreetingProps = { name: string }; class Greeting extends React.Component<GreetingProps, any> { render() { return <span>Hello, {this.props.name}!</span>; } }
1)GreetingProps是類型參數(shù)Props的類型參數(shù)
2) 類似地,any是類型參數(shù)State的類型參數(shù)
有了這些類型,咱們的組件得到更好的類型檢查和自動提示:
但是,現(xiàn)在使用React.Component類時就必需供兩種類型。咱們開著的初始代碼示例就不在正確地進行類型檢查:
// Error: 泛型類型 Component<Props, State> // 需要 2 個類型參數(shù)。 class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span>; } }
如果咱們不想指定像GreetingProps這樣的類型,可以通過為Props和State類型參數(shù)提供any類型來修正代碼:
class Greeting extends React.Component<any, any> { render() { return <span>Hello, {this.props.name}!</span>; } }
這種方法可以讓編譯器通過,但咱們還有更優(yōu)雅的做法:泛型參數(shù)默認類型。
泛型參數(shù)默認類型
從 TypeScript 2.3 開始,咱們可以為每個泛型類型參數(shù)添加一個默認類型。在下面的例子中,如果沒有顯式地給出類型參數(shù),那么Props和State都都是any類型:
declare namespace React { class Component<Props = any, State = any> { props: Props; state: State; } }
現(xiàn)在,咱們就可以不用指定泛型類型就可以通過編譯器的檢查:
class Greeting extends React.Component { render() { return <span>Hello, {this.props.name}!</span>; } }
當然,咱們?nèi)匀豢梢燥@式地為Props類型參數(shù)提供類型并覆蓋默認的any類型,如下所示:
type GreetingProps = { name: string }; class Greeting extends React.Component<GreetingProps, any> { render() { return <span>Hello, {this.props.name}!</span>; } }
這兩個類型參數(shù)現(xiàn)在都有一個默認類型,所以它們是可選的,咱們可以僅為Props指定顯式的類型參數(shù):
type GreetingProps = { name: string };
class Greeting extends React.Component<GreetingProps> { render() { return <span>Hello, {this.props.name}!</span>; } }
注意,咱們只提供了一個類型參數(shù)。但是,被省略可選類型參數(shù)前一個必須要指定類型,否則不能省略。
其它事例
在上一篇中關于 TypeScript 2.2 中混合類的文章中,咱們最初聲明了以下兩個類型別名:
type constructor<T> = new (...args: any[]) => T; type constructable = Constructor<{}>;
Constructable類型純粹是語法糖。它可以代替Constructor<{}>類型,這樣就不必每次都要寫泛型類型參數(shù)。使用泛型參數(shù)默認值,就可以完全去掉附加的可構(gòu)造類型,并將{}設置為默認類型
type Constructor<T = {}> = new (...args: any[]) => T;
語法稍微復雜一些,但是生成的代碼更簡潔,Good。
新的--strict主要編譯選項
TypeScript 2.3 引入了一個新的--strict編譯器選項,它支持許多與更嚴格的類型檢查相關的其他編譯器選項。
TypeScript 加入的新檢查項為了避免不兼容現(xiàn)有項目通常都是默認關閉的。雖然避免不兼容是好事,但這個策略的一個弊端則是使配置最高類型安全越來越復雜,這么做每次 TypeScript 版本發(fā)布時都需要顯示地加入新選項。有了--strict編譯選項,就可以選擇最高級別的類型安全(了解隨著更新版本的編譯器增加了增強的類型檢查特性可能會報新的錯誤)。
新的--strict編譯器選項包含了一些建議配置的類型檢查選項。具體來說,指定--strict相當于是指定了以下所有選項(未來還可能包括更多選項):
- --strictNullChecks
- --noImplicitAny
- --noImplicitThis
- --alwaysStrict
未來的 TypeScript 版本可能會在這個集合中添加額外的類型檢查選項。這意味著咱們不需要監(jiān)控每個 TypeScript 版本來獲得應該在項目中啟用的新嚴格性選項。如果向上述選項集添加了新選項,則在升級項目的 TypeScript 版本后,它們將自動激活。
--strict編譯選項會為以上列出的編譯器選項設置默認值。這意味著還可以單獨控制這些選項。比如:
--strict --noImplicitThis false
或者在tsconfig.json文件指定:
{ "strict": true, "alwaysStrict": false }
這將是開啟除--noImplicitThis編譯選項以外的所有嚴格檢查選項。使用這個方式可以表述除某些明確列出的項以外的所有嚴格檢查項。換句話說,現(xiàn)在可以在默認最高級別的類型安全下排除部分檢查。
改進的--init輸出
除了默認的--strict設置外,tsc --init還改進了輸出。tsc --init默認生成的tsconfig.json文件現(xiàn)在包含了一些帶描述的被注釋掉的常用編譯器選項. 你可以去掉相關選項的注釋來獲得期望的結(jié)果。我們希望新的輸出能簡化新項目的配置并且隨著項目成長保持配置文件的可讀性。
通過tsc --init編譯器可以為構(gòu)建一個配置文件:
$ 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 代碼添加某些類型信息,
以上就是TypeScript泛型參數(shù)默認類型和新的strict編譯選項的詳細內(nèi)容,更多關于TypeScript的資料請關注腳本之家其它相關文章!
相關文章
使用Auto.js?調(diào)用系統(tǒng)短信、電話模塊實現(xiàn)功能
這篇文章主要介紹了如何使用Auto.js調(diào)用系統(tǒng)短信與電話模塊,并實現(xiàn)讀取短信與聯(lián)系人的功能,并給出了實現(xiàn)相應功能的代碼2023-03-03關于Javascript加載執(zhí)行優(yōu)化的研究報告
這篇文章主要介紹了關于Javascript加載執(zhí)行優(yōu)化的研究報告,需要的朋友可以參考下2014-12-12js將json格式的對象拼接成復雜的url參數(shù)方法
下面小編就為大家?guī)硪黄猨s將json格式的對象拼接成復雜的url參數(shù)方法。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05