What's new in TypeScript

www.typescriptlang.org/docs/handbo…

With union types, you can now specify the desired behavior at both the function declaration site and the call site:

(用联合类型,在函数的声明和调用的时候,你可以指定期望的行为)

function choose1<T>(a:T , b: T): T{ return Math.random() > 0.5 ? a : b }
let a = choose1('hello',42) //error
let b = choose2<string | number>('hello',42) //OK

function choose2<T, U>(a: T, b: U): T|U{
    return Math.random() > 0.5 ? a : b
}
var c = choose2('haha','foo')//OK c:string
var d = choose2('haha',32)//OK string|number
复制代码

Better Type Inference(更好的类型推断)

Union types also allow for better type inference in arrays and other places where you might have multiple kinds of values in a collection:

(联合类型也允许更好的类型推断在数组或者是其他的有多个不同种类的集合中)

var x = [1,'hello'] //x:Array<number|string>
x[0] = 'world' // OK
x[2] = false // Error, boolean is not string or number
复制代码

let declarations

In JavaScript, var declarations are “hoisted” to the top of their enclosing scope. This can result in confusing bugs:

(在js中,var声明会在作用域中把变量提升到顶部。这可能会导致一些令人困惑的bug)

console.log(x); // meant to write 'y' here
/* later in the same block */
var x = 'hello';
复制代码

The new ES6 keyword let, now supported in TypeScript, declares a variable with more intuitive “block” semantics.

(新的ES6的let关键字,在ts中是被支持的,它声明了一个具有更直观的“块”语义的变量。)

A let variable can only be referred to after its declaration, and is scoped to the syntactic block where it is defined: (let变量只能在声明后被引用,它的作用域范围限定在它定义的语法块)

if (foo) {
    console.log(x); // Error, cannot refer to x before its declaration
    let x = 'hello';
}
else {
    console.log(x); // Error, x is not declared in this block
}
复制代码

const declarations

The other new ES6 declaration type supported in TypeScript is const.

(另一个新的声明类型在ts中也是被支持的)

A const variable may not be assigned to, and must be initialized where it is declared.

(const变量可能未被赋值,并且必须在声明它的位置初始化。)

This is useful for declarations where you don’t want to change the value after its initialization:

(这对于您不希望在初始化后更改值的声明很有用:)

const halfPi = Math.PI / 2;
halfPi = 2; // Error, can't assign to a `const`
复制代码

Template strings

TypeScript now supports ES6 template strings. These are an easy way to embed arbitrary expressions in strings:

(ts现在支持es6的模版字符串。这是一种很简单的方法你可以随意在字符串中嵌入表达式)

var name = "TypeScript";
var greeting  = `Hello, ${name}! Your name has ${name.length} characters`;
复制代码

When compiling to pre-ES6 targets, the string is decomposed:

(当编译的ES6之前的目标是,字符串被分解为:)

var name = "TypeScript!";
var greeting = "Hello, " + name + "! Your name has " + name.length + " characters";

复制代码

Type Guards

A common pattern in JavaScript is to use typeof or instanceof to examine the type of an expression at runtime. TypeScript now understands these conditions and will change type inference accordingly when used in an if block. (JavaScript中的常见模式是使用typeof或instanceof在运行时检查表达式的类型。 TypeScript现在可以理解这些条件,并且在if块中使用时会相应地更改类型推断。)

Using typeof to test a variable: (用typeof来检测一个变量)

var x: any = /* ... */;
if(typeof x === 'string') {
    console.log(x.subtr(1)); // Error, 'subtr' does not exist on 'string'
}
// x is still any here
x.unknown(); // OK
复制代码

Using typeof with union types and else:

(用typeof和联合类型还有else检测变量)

var x: string | HTMLElement = /* ... */;
if(typeof x === 'string') {
    // x is string here, as shown above
}
else {
    // x is HTMLElement here
    console.log(x.innerHTML);
}
复制代码

Using instanceof with classes and union types:

(用instanceof、classes还有联合类型检测变量)

class Dog { woof() { } }
class Cat { meow() { } }
var pet: Dog|Cat = /* ... */;
if (pet instanceof Dog) {
    pet.woof(); // OK
}
else {
    pet.woof(); // Error
}

复制代码

Type Aliases

You can now define an alias for a type using the type keyword: (你现在可以给一个类型定义一个别名用类型关键字:type)

type PrimitiveArray = Array<string|number|boolean>;
type MyNumber = number;
type NgScope = ng.IScope;
type Callback = () => void;
复制代码

Type aliases are exactly the same as their original types; they are simply alternative names.

(类型别名与其原始类型完全相同; 它们只是替代名称。)

const enum (completely inlined enums)

Enums are very useful, but some programs don’t actually need the generated code and would benefit from simply inlining all instances of enum members with their numeric equivalents.

(枚举非常有用,但是某些程序实际上并不需要生成的代码,并且只需简单地使用其数字等价物内联枚举成员的所有实例即可获益。)

The new const enum declaration works just like a regular enum for type safety, but erases completely at compile time.

(新的枚举声明就像类型安全的常规枚举一样,但在编译时会完全擦除。)

const enum Suit { Clubs, Diamonds, Hearts, Spades }
var d = Suit.Diamonds;

复制代码

Compiles to exactly:

最终编译成:

var d = 1;
复制代码

TypeScript will also now compute enum values when possible:

ts 现在也会在可能的情况下计算枚举值:

enum MyFlags {
  None = 0,
  Neat = 1,
  Cool = 2,
  Awesome = 4,
  Best = Neat | Cool | Awesome
}
var b = MyFlags.Best; // emits var b = 7;

复制代码

转载于:https://juejin.im/post/5d088fdaf265da1bb67a1ae1

猜你喜欢

转载自blog.csdn.net/weixin_34409357/article/details/93182650