Announcing TypeScript 2.0 RC August 30, 2016 by Daniel Rosenwasser
TypeScript 2.0 release candidate (RC) is out, and we’re close to TypeScript 2.0 release. If you haven’t started working with TypeScript yet, check out the tutorials on TypeScript.
To use the RC version, download TypeScript 2.0 RC for Visual Studio 2015 (VS2015 Update 3 is required); It can also be downloaded via NuGet, or NPM can be used as follows:
npm install -g typescript@rcCopy the code
Visual Studio Code users who want to use the RC version can refer here.
This RC release gives you a glimpse of what 2.0 looks like, and we’ve used it to gather feedback and make 2.0 more stable and reliable. Overall, the RC version is generally stable enough, and we don’t want to add new features.
However, a lot has been added since the 2.0 Beta release, so there may be new features that you haven’t heard of yet.
Inferred Types (Tagged Unions)
.
For the translation of Tagged Unions, I have checked many materials and found the following description on wiki: A tagged union, also called a variant, variant record, discriminated union, disjoint union, or sum type. The term Variant is commonly used in VB. After looking at C#’s translation of the var keyword, I decided to translate it as “inferred type.”
Inferred type is a data structure, much like union (a structure that C/C++ programmers must know about). It has a field (or property) that identifies the exact type of the current structure. (See What is a tagged Union)
Inferred types make JavaScript more like F#, Swift, etc., in some ways. JavaScript programmers must be very happy about this. This feature is also known as recognized union, mutex union, or proxy types. But the feature itself is obviously more interesting than the name.
Suppose you have two types: Circle and Square, and then define their combined type and name it Shape.
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;Copy the code
Notice that both Circle and Square have a field called kind, which holds a string constant that represents the type. So Circle’s kind is always “Circle”. Each type has a common field, but is distinguished by different values as tokens.
In TypeScript 1.8, if you write a function that gets an area, you need to determine each type of Shape.
function getArea(shape: Shape) { switch (shape.kind) { case "circle": // Convert from 'Shape' to 'Circle' let c = Shape as Circle; return Math.PI * c.radius ** 2; Case "square": // convert from 'Shape' to 'square' let sq = Shape as square; return sq.sideLength ** 2; }}Copy the code
Notice that we use an intermediate variable for each graph to keep the code simple.
Intermediate variables are no longer needed in 2.0. The language knows how to recognize types by kind, so you can write less code, right
function getArea(shape: Shape) { switch (shape.kind) { case "circle": // where 'shape' is 'Circle' return math.pi * shape.radius ** 2; Case "square": // where 'shape' is' square 'return shape. SideLength ** 2; }}Copy the code
The above code is perfectly correct, and TypeScript analyzes the correct type on each branch through flow control. You can use the –noImplicitReturns and the upcoming –strictNullChecks feature to make these checks more thorough.
Inferred types make code in this form of JavaScript much cleaner and safer. For example, libraries like Redux often use this form to handle actions. Each individual
More literal types
The string literal types that come with 1.8 are very useful for handling inferred types, as you can see above.
We want to provide more types than just strings. In 2.0, each unique Boolean, numeric, or enumerator can have its own type!
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; let nums: Digit[] = [1, 2, 4, 8]; / / error! '16' not 'Digit! nums.push(16);Copy the code
This allows us to do things quickly and without any sense of conflict when using inference types.
interface Success {
success: true;
value: T;
}
interface Failure {
success: false;
reason: string;
}
type Result = Success | Failure;Copy the code
The Result type here may indicate failure. It has a value if it represents success, and if it represents failure, it contains the RESon field indicating the cause of the failure. The value field is only valid if SUCCESS is true.
declare function tryGetNumUsers(): Result; let result = tryGetNumUsers(); If (result.success === true) {// 'result' is console.log(' Server reported ${result.value} users'); } else {// 'result' is console.error("Error fetching number of users!" , result.reason); }Copy the code
As you may have noticed, enumerated values can also have their own types!
enum ActionType { Append, Erase } interface AppendAction { type: ActionType.Append; text: string; } interface EraseAction { type: ActionType.Erase; numChars: number; } function updateText(currentText: string, action: AppendAction | EraseAction) { if (action.type === ActionType.Append) { // 'action' has type 'AppendAction' return currentText + action.text; } else { // 'action' has type 'EraseAction' return currentText.slice(0, -action.numChars); }}Copy the code
Globs syntax, include, and exclude
.
Globs literally means “lump,” but that’s not as clear as Globs itself. So I’m not translating the word here. For Globs, see node-blog’s description in readme.md.
When I first introduced you to the tsconfig.json file, it was a pain to list all the files by hand. TypeScript 1.6 introduces the Excludes configuration to alleviate this problem; However, this is clearly not enough. The pain is that after writing every file path, problems still occur because you forgot to exclude new files.
TypeScript 2.0 is finally starting to support Globs syntax. Globs allows us to use wildcards in paths so that writing paths is no longer a chore.
Globs syntax can be used in both include and exclude configurations. Let’s look at an example of tsconfig.json:
{
"include": [
"./src/**/*.ts"
],
"exclude": [
"./src/tests/**"
]
}Copy the code
TypeScript Globs syntax supports the following wildcards:
-
* Matches zero or more characters, except delimiters (such as/or \)
-
? Matches exactly 1 character, excluding delimiters
-
**/ Matches any level subdirectory
Next thing
As mentioned earlier, TypeScript 2.0 will soon be released, but the use of new features in the RC version of TypeScript 2.0 will have a huge impact on the community.
If you find any problems, let us know via Github. We’d love to hear your feedback after you try it out. I wish happy!