TypeScript Release Note Rundown

354 阅读10分钟

Source: What's New? Overview

在官方Release notes中搜索:

KEYWORD site:www.typescriptlang.org/docs/handbo…

我将每个Release Note分类,并加上相对容易识别的emoji图标,方便后期翻阅。 还会给个别更新对应的PR链接或commit SHA1

  • ⭐️: New Features/Syntax
  • 🌟: Type Related
  • 🔑: Keyword Related
  • 🎗: Modifier Related
  • 🚩: Flag related
  • 🏷: Tag related
  • 💔: Breaking Change
  • 🔧: Config Related
  • ✅: Checking Related or become more strict
  • 〰: Inline comment
  • 📦: Module Related
  • 👩‍🏫: Class Related
  • 🧮: Function Releated
  • ⤵️: Support advanced feature in low targets (Downlevel ...)
  • ⚛️: React related
  • ⏫: Improvements/Enhancement
  • 👽: Peripherals
  • 🍎: A Relase with numerous features/improvments
  • ⬅️: Needs special attention
  • 🥑:Well-known feature

Skipped versions: 1.2, 1.9

标题解释:版本链接-tag链接-tag日期

Excerpt:

  • 1.4: Union Types, Template strings, Type Aliases, const enum
  • 1.8: String literal types
  • 2.0: Type widening, never type
  • 2.1: Mapped Type;
  • 3.2: BigInt
  • 4.1: Template literal types

Timeline

  • 2014: 1.1, 1.3
  • 2015: 1.4, 1.5, 1.6, 1.7
  • 2016: 1.8, 2.0, 2.1
  • 2017: 2.2, 2.3, 2.4, 2.5, 2.6
  • 2018: 2.7, 2.8, 2.9, 3.0, 3.1, 3.2
  • 2019: 3.3, 3.4, 3.5, 3.6, 3.7
  • 2020: 3.8, 3,9, 4.0, 4.1
  • 2021: 4.2, 4.3, 4.4

1.1 🔖 2014/09/18

  • Performance Improvements
  • 🚩📦 Better Module Visibility Rules (--declaration)

1.3 🔖 2014/10/28

  • 👩‍🏫🎗 protected modifier in classes
  • 🌟 Tuple types ⬅️ 🥑

1.4 🔖 2015/01/14

  • 🌟 Union types ⬅️ 🥑
  • Stricter Generics
  • Better Type Inference
  • 🔑 let declarations (--target>es6)
  • 🔑 const declarations (--target>es6)
  • ⭐️ Template strings ⬅️ 🥑
  • ⭐️ Type Guards (@see v1.5 User-defined...)
  • ⭐️ Type Aliases ⬅️ 🥑
  • ⭐️ const enum ⬅️
  • 🚩 -noEmitOnError
  • 🏷📦 <amd-module name="..."/>

1.5 🔖 2015/04/28

  • ⭐️📦 ES6 Module
  • ⭐️ Destructuring in declarations and assignments
  • 🔑 namespace keyword
  • ⭐️ Decorators ⬅️
  • ⭐️ Computed properties
  • 📦 --module=umd|system
  • Unicodde codepoint escapes in strings
  • ⤵️ Tagged template string in ES3/ES5
  • 🏷 <amd-dependency path="..." />
  • 🔧 Project support throught tsconfig.json
  • 🚩 --rootDir
  • 🚩 --noEmitHelpers
  • 🚩 --newLine
  • 🚩 --inlineSourceMap and inlineSources

1.6 🔖 2015/08/29

  • 🌟 JSX Support ⬅️
  • 🌟 Intersection types ⬅️ 🥑
  • 🌟 Local type declarations (block scoped)
  • 🔑 class, extends,abstract
  • 🧡 Generic type aliases
  • ✅ Stricter object literal assignment checks
  • ⭐️ ES6 generator ⬅️
  • 🔑 async
  • Nightly builds (npm i typescript@next)
  • 📦 Adjustment in module resolution logic
  • 🧡 Mergin ambient class and interface declaration
  • User-defined type guard functions
  • 🔧 exclude in tsconfig.json
  • 🚩--init

1.7 🔖 2015/10/17

  • 🔑 async/await support in ES6 targets
  • 🚩 Support for --target es6 with --module
  • 🧡 this typing (methods return type annotation)
  • ⭐️ ES7 exponentiation operator
  • ✅ Improved checking for destructuring object literal
  • ⤵️ Support for decorators when targeting ES6

1.8🍎 🔖 2016/01/28

  • 🧮 Type parameters as constraints (F-Bounded Polymorphism)
  • Control flow analysis errors ⬅️
  • 🚩 --allowUnreachableCode ,--allowUnusedLabels,--noFallthroughCasesInSwitch,
  • ⚛️ 🧮 Function Components in React
  • ⚛️ Simplified props type management in React
  • Agumenting global/module scope from modules
  • 🌟 String literal types ⬅️ 🥑
  • ⏫🌟 Improved union/intersection type inference
  • 🚩 Concatenate AMD and System modules with --outFile
  • 🚩 --allowSyntheticDefaultImports Support for default import interop with SystemJS
  • ⏫ Allow captured let/const in loops
  • ✅ Improved checking for for..in statements
  • 📦 Modules are now emitted with a "use strict" prologue
  • 🚩 Including .js files with --allowJS
  • 🚩 Custom JSX factories using --reactNamespace
  • 🌟 this -based type gurad
  • 👽 Offical TypeScript NuGet package
  • Prettier error message from tsc
  • 👽 Colorization of JSX code in VS 2015
  • 🚩 The --project -p flag can now take any file path
  • 🔧 Allow comments in tsconfig.json
  • 🚩 Support output to IPC -driven files (--outFile) ⬅️
  • 👽 Improved support for tsconfig.json in VS 2015

2.0🍎 🔖 2016/07/08

  • 🌟 Null- and undefined-aware types (null和undefined可以被作为类型名使用..)
  • 🚩 --strictNullChecks
  • 🌟 Assigned-before-use checking
  • 🌟🧮 Optional parameters and properties
  • 🌟 Optional class properties
  • 🌟 Non-null and non-undefiend type guards
  • ⏫ Dotted names in type guards
  • Expression operator
  • 🌟 Type widening ⬅️ 🥑
  • 🌟 Non-null assertion operator (!. operator)
  • 🌟 Control flow based type analysis ⬅️
  • 🌟 Tagged union types (string literal only, later add support for boolean and numeric literal tyeps)
  • 🌟 The never type ⬅️ 🥑
  • 🎗 Read-only properties and index signatures
  • 🌟 Specifying the type of this for functions
  • 🌟🧮 this parameters in callbacks
  • 🚩 --noImplicitThis
  • 🔧 Glob support in tsconfig.json
  • ⏫📦 Module resolution enhancements
  • 🔧 Virtual Directories with rootDirs
  • 🚩📦 Tracing module resolution with --traceResolution
  • 📦 Shorthand ambient module declrations
  • 📦 Wildcard character in module names
  • 📦 Support for UMD module definitions
  • 👩‍🏫 Private and Protected constructors
  • 👩‍🏫 Abstract properties and accessors
  • 🧮 Implicit index signatures
  • 🚩 Including built-in type declarations with --lib
  • 🚩 Flag unused declarations with noUnusedParameters and --noUnusedLocals
  • 📦 Module identifiers allow for '.js' extensions
  • 🔧 Support target: es5 with module: es6
  • 🧮 Trailing commas in function parameter and argument lists
  • 🚩 --skipLibCheck
  • Allow duplicate identifiers across declarations
  • 🚩 --declarationDir

这个Release处理了一系列module相关的问题

2.1 🔖 2016/08/26

  • 🌟 keyof and Lookup Types ⬅️
  • 🌟 Mapped Types ⬅️ 🥑
  • 🌟 Partial,Readonly,Record, and Pick
  • ⭐️ Object Spread and Rest
  • ⤵️ Downlevel Async Functions
  • Support for external helpers library (tslib)
  • Untyped imports (import js only modules will not an error)
  • 🚩 Support for --target es2016 es2017 esnext
  • ⏫ Improved any Inference
  • Implicit any errors
  • ⏫ Better inference for literal types
  • ⏫ Use returned values from super calls as this
  • 🔧 Configuration inheritance
  • 🚩 --alwaysStrict

2.2 🔖 2017/02/01

  • Support for Mix-in classes
  • 🌟 object type: any thing that is not number,string,boolean,symbol,null,undefined, for APIs like Object.create(object | null) ⬅️
  • ⭐️ Support for new.target
  • ✅ Better checking for null/undefined in operands of expressions
  • 🌟 Dotted property for types with striing index signatures
  • ⚛️ Support for spread operator on JSX element children
  • ⚛️ New jsx: react-native.Allow jsx in *.js file for RN

这个Release处理了一系列的rest, spread的问题

2.3🔖 2017/04/04

  • 🚩⤵️ Generators and Iteration for ES5/ES3, --downlevelIteration
  • ⭐️ Async Iteration; The for-await-of Statement ⬅️
  • 🌟 Generic parameter defaults ⬅️
  • 🚩 New --strict master option
  • 🔧 Enhanced --init output
  • 🚩〰 Errors in .js files with --checkJS, (// @ts-nocheck)

2.4🔖 2017/06/12

  • ⭐️ Dynamic Import Expressions: await import("...")
  • 🌟 String Enums

注意:初始化为字符串的枚举是没有逆向映射的

  • ⏫ Improved inference for generics
  • 🌟 Strict contravariance for callback parameters ⬅️
  • 💔🌟 Weak Type Detection

Any type that contains nothing but all-optional properties is considered Weak' it’s now an error to assign anything to a weak type when there’s no overlap in properties

// Weak Type Example
interface Options {data?: string; timeout?: number; maxRetries?: number;}

2.5🔖 2017/08/15

  • ⭐️ Optional catch clause variables
  • 〰 Type assertion/cast syntax in checkJS/@ts-check mode
  • ⏫ Dedumplicated and redirected packages
  • 🚩 --preserveSymlinks compiler flag

2.6🔖 2017/10/04

  • ✅ Strict function type ⬅️

Under --strictFunctionTypes function type parameter positions are checked contravariantly instead of bivariantly.

  • ⏫ Cache tagged template objects in modules
  • 🚩 Localized diagnostics on the command line. --locale

tsc --locale zh-CN

  • 〰 Suppress errors in .ts files using ’// @ts-ignore’ comments
  • ⏫ Faster tsc --watch
  • 🚩 Write-only references now flagged as unused. --noUnusedLocals, --noUnusedParameters

2.7🔖 2018/01/10

  • ⭐️ Constant-named properties
export const SERIALIZE = Symbol("serialize-method-key");
export interface Serializable {
  [SERIALIZE](obj: {}): string;
}
  • 🌟 unique symbol

unique symbol only allowed on const declarations and readonly static properties. Because each unique symbol has a completely separate identity, no two unique symbol types are assignable or comparable to each other.

  • ✅ Strict Class Initialization
  • ⭐️ Definite Assignment Assertion
let x!: number
  • 🌟💔 Fixed Length Tuples
type T1 = [number, string, string];
type T2 = [number, string];
declare var a: T1;
declare var b: T2;
b = a; // Error since TS2.7
  • ⏫ Improved handling of structurally identical classes and instanceof expressions
  • 🌟 Type guards inferred from in operator (act as a narrowing expressions for types)
  • 🚩📦 Support for import d from 'cjs' from CommonJS modles with --esModuleInterop
  • ⭐️ Numeric separators
const million = 1_000_000;
const phone = 555_734_2231;
const bytes = 0xff_0c_00_ff;
const word = 0b1100_0011_1101_0001
  • 🚩 Cleaner output in --watch mode
  • 🚩 Prettier --pretty output

!!! 从TS2.8之后才有的条件类型。才能用@type-challenges/utils中的Equal<X,Y> !!!

2.8 🔖 2018/03/13

  • 🌟 Conditional Types ⬅️ 🥑

57ca7680c9 - Tue Dec 5 14:18:11 2017 - Initial implementation of conditional type operator - Anders Hejlsberg

  • 🌟 Distributive conditional types ⬅️ 🥑
  • 🌟 Type inference in conditional types
  • Predefined conditional types
  • 🎗⏫ Improved control over mapped type modifiers
  • Improved keyof with intersection types
  • Better handling for namespace patterns in .js files
  • IIFEs as namespace declarations
  • Defaulted declarations
  • Prototype assignment
  • Nested and merged declarations
  • ⚛️ Per-file JSX factories ⬅️
  • Locally scoped JSX namespaces
  • 🚩 New --emitDeclarationOnly

2.8增加、加强了很多创建Mapped Type相关的特性

2.9 🔖 2018/05/14

  • 🌟 Support number and symbol named properties with keyof and mapped type ⬅️
  • ⚛️ Generic type arguments in JSX elements
  • ⚛️ Generic type arguments in generic tagged templates
  • import types
  • Relaxing declaration emit visibility rules
  • ⭐️ Support for import.meta
  • 🚩 New --resolveJsonModule
  • 🚩 --pretty output by default
  • 🚩 New --declarationMap

3.0 🔖 2018/07/12

  • 🚩 Project References, --build
  • ⭐️ Tuple in rest parameters and spread expressions
  • ⭐️ Generic rest parameters
  • ⭐️ Optional elements in tuple types
  • 🌟💔 New unknown top type ⬅️ 🥑 PR ahejlsberg:"Technically a breaking change since unknown becomes a reserved type name`"
  • ⚛️ Support for defaultProps in JSX

3.1 🔖 2018/09/11

  • 🌟 Mapped types on tuples and arrays ⬅️
  • Properties declarations on functions
  • Version selection with typesVersion

3.2 🔖 2018/11/12

  • 🚩💔 --strictBindCallApply
  • 🌟 Generic spread expressions in object literals
  • 🌟 Generic object rest variables and paramters
  • BigInt (target=esnext)
  • Non-unit types as union discriminants
  • 🔧 tsconfig.json inheritance vai Node.js packages
  • 🚩 New --showConfig flag
  • Object.defineProperty declarations in JavaScript

3.3 🔖 2019/01/22

  • ⏫ Improved behavior for calling union types
  • ⏫ Incremental file watching for composite projects in --build --watch

3.4 🔖 2019/05/15

  • 🚩 Faster subsequent builds with the --incremental flag
  • Higher order type inference from generic functions
  • Improvements for ReadonlyArray and readonly tuples PR by ahejlsberg
  • const assertion ⬅️ 🥑
  • ✅ Type-checking for globalThis

3.5 🔖 2019/05/28

  • ⏫ Speed improvements
  • The Omit Helper type PR
  • 🚩 The --allowUmdGlobalAccess flag
  • ✅ Smarter union type checking
  • Higher order type inference from generic constructors

3.6 🔖 2019/08/16

  • ✅ Stricter Generator
  • ⏫ More Accurate Array Spread (__spreadArrays)
  • ⏫ Improved UX Around Promises
  • ⏫ Better Unicode Support for Identifiers
  • import.meta Support in SystemJS
  • get and set Accessors are allowed in ambient contexts
  • Ambient classes and functions can merge
  • 🚩 APIs to Support --build and --incremental: createIncrementalProgram, createIncrementalCompilerHost,readBuilderProgram,createSolutionBuilder
  • 👽 Semicolon-Aware code edits
  • ⏫ Smarter auto-import syntax
  • 👽 New TypeScript playground

3.7 🔖 2019/10/23

  • ⭐️ Optional Chaning (?. operator: obj?.prop, arr?.[0], fn?.(arg)) ⬅️
  • ⭐️ Nullish Coalescing ⬅️
  • ⭐️ Assertion Function (playground) function f(): asserts param is 1 | 3 | 5

Assertion functions are siblings to Type Guards

  • Better support for never-returning functions❓
  • (More) Recursive type aliases (Recursive Data Type)
  • 🚩 --declaration and --allowJs (allows the two options to be used together)
  • The useDefineForClassField flag and the declare property modifier
  • Build-Free Editing with Project References❓
  • Uncalled Function Checks
  • //@ts-nocheck in TypeScript files
  • 👽 Semicolon Formatter Option
  • 💔 Breaking Changes

3.8 🔖 2020/02/05

  • ⭐️ Type-Only Imports and Exports ⬅️
  • ⭐️ ECMAScript Private Fields (this.#name) ⬅️❓
  • 📦 export * as ns Syntax
  • Top level await
  • es2020 for target and module (bigint...)
  • JSDoc property modifiers: @ts-check, @public, @protected, @private, @readonly
  • Better directory watching on Linux and watchOptions
  • “Fast and Loose” Incremental Checking❓

3.9 🔖 2020/04/26

  • ⏫ Improvements in Inference and Promise.all
  • ⏫ Speed Improvements (extremely poor editing/compilation speed with material-ui and styled-components)
  • // @ts-expect-error Comments

Pick ts-expect-error if:

  • you’re writing test code where you actually want the type system to error on an operation
  • you expect a fix to be coming in fairly quickly and you just need a quick workaround
  • you’re in a reasonably-sized project with a proactive team that wants to remove suppression comments as soon affected code is valid again Pick ts-ignore if:
  • you have a larger project and new errors have appeared in code with no clear owner
  • you are in the middle of an upgrade between two different versions of TypeScript, and a line of code errors in one version but not another.
  • you honestly don’t have the time to decide which of these options is better.
  • Uncalled function checks in conditional expression
  • ⏫ Editor improvements
    • CommonJS Auto-Imports in JavaScript
    • Code action preserve newline
    • Quick fixes for missing return expressions
    • Support for "Solution Style" tsconfig.json files
  • 💔 Breaking changes
    • Parsing differences in optional chaning and Non-null assertions
    • } and > are now invalid JSX text characters (用 &gt 转译或 {'}'},{'>'}) 36636
    • ✅ Stricter checks on intersections and optional properties
    • Intersections reduced by distriminant properties
    • Getters/Setters are no longer enumerable 32264
    • Type parameters that extend any no longer act as any
    • export * is always retained
    • More libdom.d.ts refinements

4.0 🔖 2020/08/06

  • ⭐️ Variadic tuple types⬅️
  • ⭐️ Labeled tuple elements
  • Class property inference from constructors
  • Short-circuiting assignment operators
  • unknown on catch clause bindings
  • Custom JSX Factories
{
    "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "jsx": "react",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment"
}
  • 🚩⏫ Speed improvments in build mode with --noEmitOnError
    • --incremental with --noEmit
  • ⏫ Editor imporvements
    • Select different versions of TypeScript
    • JavaScript/TypeScript Nightly Extension
    • Convert to Optional Chaining
    • /** @deprecated */ support
    • Partial semantic mode at startup
    • Smarter auto-imports
  • 💔 Breaking changes
    • lib.d.ts changes
    • Properties overriding accessors(and vice versa) is an Error
    • Operands for delete must be optional
    • Usage of TypeScript's Node Factory is Deprecated

4.1 🔖 2020/11/02

  • ⭐️Template literal types⬅️
  • Key remapping in mapped types (as clause in mapped type) image.png
  • Recursive conditional types (40002) image.png
  • 🚩 Checked indexed accesses (--noUnchecedIndexedAccess)
  • 🔧paths without baseUrl
  • 🔧checkJs implies allowJs
  • ⚛️ React 17 JSX Factories
{"compilerOptions": {"jsx": "react-jsx"}}
{"compilerOptions": {"jsx": "react-jsxdev"}}
  • Editor support for the JSDoc @see Tag
  • Breaking changes
    • lib.d.ts changes
    • abstract members can't be marked async ⬅️
    • any/unknown are propagated in Falsy positions
    • resolve's parameters are no longer optional in Promises (except Promise<void>)
    • Conditional spread create optinal properties
    • Unmatched parameters are no longer related

4.2 🔖 2021/02/10

  • Smarter type alias preservation
  • ⭐️ Leading/Middle rest elements in tuple types

only one rest element per tuple, and no optional elements after rest elements

  • ✅ Stricter checks for the in operator
  • 🚩 --noPropertyAccessFromIndexSignature 40171
  • ⭐️ abstract construct signatures
  • ⭐️ 🚩 Understanding your project structure with --explainFiles
  • ⏫ Improved uncalled function checks in logical experssions
  • ⭐️ Destructured variables can be explicitly marked as unused 41378
  • Relaxed rules between optional properties and string index signatures 41921
  • 👽 Declare missing helper function
  • 💔 Breaking changes
    • lib.d.ts updates
    • noImplicitAny errors apply to loose yield expressions
    • Exapaned uncalled function checks
    • Type arguments in JavaScript are not parsed as type arguments
    • Tuple size limits for spreads
    • .d.ts extensions cannot be used in import paths
    • Reverting template literal inference
    • TypeScript's lift callback in visitNode uses a different type

4.3 🔖 2021/05/10

  • ⏫ Separate write types on properties

Before 4.3, it will be an error when get and set have different type image.png

  • ⭐️ 🚩override(keyword) and the --noImplicitOverride flag

When a method is marked with override, TypeScript will always make sure that a method with the same name exists in a the base class.

  • ⏫ Template string type improvements ⬅️
  • ECMAScript #private class elements
class Foo {
  #someMethod() {}
  get #someValue() {}
}
  • ConstructorParameters works on abstract classes
  • ⏫ Contextual narrowing for generics
  • ⏫ Always-Truthy promise checks
  • static index signatures ⬅️ 37797 by Kingwl
  • .tsbuildinfo size improvements
  • Lazier calculations in --incremental and --watch compilations
  • Import statement completions
  • Editor support for @links tags
  • Go-to-definition on Non-JavaScript file paths
  • 💔 Breaking Changes
    • libd.ts chagnes
    • useDefineForClassFields default to true on esnext
    • Errors on alwasy-truthey promise checks
    • Union enums cannot be compared to arbitarary numbers

4.4 🔖 2021/08/27

  • Control flow analysis of aliased conditions and discriminants

原来用于narrow的条件必须在if的括号里。现在可以将条件赋值给const、readonly property或未修改的parameter。同时,从distriminants中结构出来的属性也可以赋值给const等,用于narrowing。

  • Symbol and template string pattern index sigunatures
  • Defaulting to the unknown type in catch variables(--useUnknownInCatchVariables)
  • Exact optional property types(--exactOPtionalPropertyTypes)
  • ⭐️ static blocks in classes
  • tsc --help updates and improvents
  • Performance improvements
    • Faster declaration emit
    • Faster path normalization
    • Faster path mapping
    • Faster incremental builds with --strict
    • Faster source map generation for big outputs
    • Faster --force builds
  • Spelling suggestions for JavaScript
  • Inlay Hints by Kingwl
  • Auto-imports show true paths in completion lists
  • 💔 Breaking changes
    • lib.d.ts changes for TypeScript 4.4
    • More-compliant indirect calls for imported functions
    • Using unknown in catch variables
    • Broader always-truthy promise check
    • Abstract properties do not allow initializers

4.5 beta 🔖 2021/10/02

  • 📦 ECMAScript Module Support in Node.js

{ "compilerOptions": { "module": "nodenext" } }

  • type in package.json and New Extensions

Node.js supports a new setting in package.json called type"type" can be set to either "module" or "commonjs"

  • Supportinglibfromnode_modules
  • TheAwaitedType andPromiseImprovements Commit
  • Template String Types as Discriminants
  • module es2022
  • Tail-Recursion Elimination on Conditional Types
  • Disabling Import Elision
  • typeModifiers on Import Names
  • Private Field Presence Checks
  • Faster Load Time withrealPathSync.native
  • ⚛️ Snippet Completions for JSX Attributes
  • Better Editor Support for Unresolved Types
  • Breaking Changes