Cool New Features Released with TypeScript 3.6
Lots of new features are released with TypeScript 3.6. It includes features for iterables such as stricter type checking for generators, more accurate array spreading, allow get
and set
in declare
statements, and more.
In this article, we’ll look at each of them.
Stricter Type Check for Generators
With TypeScript 3.6, the TypeScript compiler has more checks for data types in generators.
Now we have a way to differentiate whether our code yield
or return
from a generator.
For example, if we have the following generator:
function* bar() {
yield 1;
yield 2;
return "Finished!"
}let iterator = bar();
let curr = iterator.next();
curr = iterator.next();if (curr.done) {
curr.value
}
The TypeScript 3.6 compiler knows automatically that curr.value
is a string since we returned a string at the end of the function.
Also, yield
isn’t assumed to be of any
type when we assign yield
to something.
For instance, we have the following code:
function* bar() {
let x: { foo(): void } = yield;
}let iterator = bar();
iterator.next();
iterator.next(123);
Now the TypeScript compiler knows that the 123 isn’t assignable to something with the type { foo(): void }
, which is the type of x
. Whereas in earlier versions, the compiler doesn’t check the type of the code above.
So in TypeScript 3.6 or later, we get the error:
Argument of type '[123]' is not assignable to parameter of type '[] | [{ foo(): void; }]'.Type '[123]' is not assignable to type '[{ foo(): void; }]'.Type '123' is not assignable to type '{ foo(): void; }'.
Also, now the type definitions for Generator
and Iterator
have the return
and throw
methods present and iterable.
TypeScript 3.6 converts the IteratorResult
to the IteratorYieldResult<T> | IteratorReturnResult<TReturn>
union type.