Introduction New Features in TypeScript 3.7 and How to Use Them

Introduction New Features in TypeScript 3.7 and How to Use Them

The TypeScript 3.7 release is coming soon, and it's going to be a big one.

The target release date is November 5th, and there are some seriously exciting headline features included:

  • Assert signatures.
  • Recursive type aliases.
  • Top-level await.
  • Null coalescing.
  • Optional chaining.

Personally, I'm super excited about this, they're going to whisk away all sorts of annoyances that I've been fighting in TypeScript while building HTTP Toolkit.

If you haven't been paying close attention to the TypeScript development process though, it's probably not clear what half of these mean, or why you should care. Let's talk through all of them.

Assert Signatures

This is a brand-new and little-known TypeScript feature, which allows you to write functions that act like type guards as a side-effect, rather than explicitly returning their boolean result.

It's easiest to demonstrate this with a JavaScript example:

function assertString(input) { 
  if (typeof input === 'string') 
    return; 
  else 
    throw new Error('Input must be a string!'); 
} 
function doSomething(input) { 
  assertString(input); 
  // ... Use input, confident that it's a string 
} 
doSomething('abc'); 
// All good doSomething(123); // Throws an error

This pattern is neat and useful, and you can't use it in TypeScript today.

TypeScript can't know that you've guaranteed the type of input after it's run assertString. Typically, people just make the argument input: string to avoid this, and that's good. But, it also just pushes the type checking problem somewhere else, and in cases where you just want to fail hard, it's useful to have this option available.

Fortunately, soon we will:

// With TS 3.7 
function assertString(input: any): 
	asserts input is string { 
      // <-- the magic 
      if (typeof input === 'string') 
        return; 
      else 
        throw new Error('Input must be a string!'); 
    } 
function doSomething(input: string | number) { 
  assertString(input); 
  // input's type is just 'string' here }

Here assert input is string means that if this function ever returns, TypeScript can narrow the type of input to string, just as if it was inside an if block with a type guard.

To make this safe, that means if the assert statement isn't true then your assert function must either throw an error or not return at all (kill the process, infinite loop, you name it).

That's the basics, but this actually lets you pull some really neat tricks:

// With TS 3.7 
// Asserts that input is truthy, throwing immediately if not: 
function assert(input: any): 
	asserts input { // <-- not a typo 
      if (!input) 
        throw new Error('Not a truthy value'); 
    } 
declare const x: number | string | undefined; 
assert(x); // Narrows x to number | string 
// Also usable with type guarding expressions! 
assert(typeof x === 'string'); 
// Narrows x to string // -- Or use assert in your tests: -- 
const a: Result | Error = doSomethingTestable(); 
expect(a).is.instanceOf(result); 
// 'instanceOf' could 'asserts a is Result' 
expect(a.resultValue).to.equal(123); 
// a.resultValue is now legal // -- Use as a safer ! that throws immediately if 
// you're wrong -- 
function assertDefined<T>(obj: T): 
	asserts obj is NonNullable<T> { 
      if (obj === undefined || obj === null) { 
        throw new Error('Must not be a nullable value'); 
      } 
    } 
declare const x: string | undefined; 
// Gives y just 'string' as a type, could throw elsewhere later: 
const y = x!; 
// Gives y 'string' as a type, or throws immediately if you're wrong: 
assertDefined(x); const z = x; 
// -- Or even update types to track a function's side-effects -- 
type X<T extends string | {}> = { value: T }; 
// Use asserts to narrow types according to side effects: 
function setX<T extends string | {}>(x: X<any>, v: T): 
	asserts x is X<T> { 
      x.value = v; 
    } 
	declare let x: X<any>; 
// x is now { value: any }; 
setX(x, 123); 
// x is now { value: number };

This is still in flux, so don't take it as the definite result, and keep an eye on the pull request if you want the final details.

There's even a discussion there about allowing functions to assert something and return a type, which would let you extend the final example above to track a much wider variety of side effects, but we'll have to wait and see how that plays out.

Top-Level Await

Async/await is amazing and makes promises dramatically cleaner to use.

Unfortunately, though, you can't use them at the top level. This might not be something you care about much in a TS library or application, but if you're writing a runnable script or using TypeScript in a REPL, then this gets super annoying.

It's even worse if you're used to frontend development, since top-level await has been working nicely in the Chrome and Firefox console for a couple of years now.

Fortunately though, a fix is coming. This is actually a general stage-3 JS proposal, so it'll be everywhere else eventually too, but for TS devs 3.7 is where the magic happens.

This one's simple, but let's have another quick demo anyway:


// Your only solution right now for a script that does something async: 
async function doEverything() { 
  ... 
  const response = await fetch('http://example.com'); 
  ... 
} 
  
doEverything(); // <- eugh (could use an IIFE instead, but even more eugh)

With top-level await:

// With TS 3.7: 
// Your script: ... 
const response = await fetch('http://example.com'); 
// ...

There's a notable gotcha here: if you're not writing a script, or using a REPL, don't write this at the top level, unless you really know what you're doing!

It's totally possible to use this to write modules that do blocking async steps when imported. That can be useful for some niche cases, but people tend to assume that their import statement is a synchronous, reliable, and fairly quick operation, and you could easily hose your codebase's startup time if you start blocking imports for complex async processes (even worse, processes that can fail).

This is somewhat mitigated by the semantics of imports of async modules: they're imported and run in parallel, so the importing module effectively waits for Promise.all(importedModules) before being executed.

Rich Harris wrote an excellent piece on a previous version of this spec before that change when imports ran sequentially and this problem was much worse), which makes for good background reading on the risks here if you're interested.

It's also worth noting that this is only useful for module systems that support asynchronous imports. There isn't yet a formal spec for how TS will handle this, but that likely means that a very recent target configuration, and, either ES Modules or Webpack v5 (whose alphas have experimental support), will be used at runtime.

Recursive Type Aliases

If you're ever tried to define a recursive type in TypeScript, you may have run into StackOverflow questions like this: https://stackoverflow.com/questions/47842266/recursive-types-in-typescript.

Right now, you can't. Interfaces can be recursive, but there are limitations to their expressiveness, and type aliases can't. That means right now, you need to combine the two: define a type alias and extract the recursive parts of the type into interfaces. It works, but it's messy, and we can do better.

As a concrete example, this is the suggested type definition for JSON data:

type JSONValue = | string | number | boolean | JSONObject | JSONArray; 
interface JSONObject { [x: string]: JSONValue; } 
interface JSONArray extends Array<JSONValue> { }

That works, but the extra interfaces are only there because they're required to get around the recursion limitation.

Fixing this requires no new syntax; it just removes that restriction, so the below compiles:

// With TS 3.7: 
type JSONValue = | string | number | boolean | { [x: string]: JSONValue } | Array<JSONValue>;

Right now, that fails to compile with Type alias 'JSONValue' circularly references itself. Soon though, soon...

Null Coalescing

Aside from being difficult to spell, this one is quite simple and easy. It's based on a JavaScript stage-3 proposal, which means it'll also be coming to your favorite vanilla JavaScript environment soon (if it hasn't already).

In JavaScript, there's a common pattern for handling default values, and falling back to the first valid result of a defined group. It looks something like this:

// Use the first of firstResult/secondResult which is truthy: 
const result = firstResult || secondResult; 
// Use configValue from provided options if truthy, or 'default' if not: 
this.configValue = options.configValue || 'default';

This is useful in a host of cases, but due to some interesting quirks in JavaScript, it can catch you out. If firstResult or options.configValue can meaningfully be set to false, an empty string or 0, then this code has a bug. If those values are set, then when considered as booleans they're falsy, so the fallback value (secondResult / 'default') is used anyway.

Null coalescing fixes this. Instead of the above, you'll be able to write:

// With TS 3.7: 
// Use the first of firstResult/secondResult which is *defined*: 
const result = firstResult ?? secondResult; 
// Use configSetting from provided options if *defined*, or 'default' if not: 
this.configValue = options.configValue ?? 'default';

?? differs from || in that it falls through to the next value only if the first argument is null or undefined, not falsy. That fixes our bug. If you pass false as firstResult, that will be used instead of secondResult because, while it's falsy, it is still defined, and that's all that's required.

It's simple but super-useful, as it takes away a whole class of bugs.

Optional Chaining

Last but not least, optional chaining is another stage-3 proposal that is making its way into TypeScript.

This is designed to solve an issue faced by developers in every language: how do you get data out of a data structure when some or all of it might not be present?

Right now, you might do something like this:

// To get data.key1.key2, if any level could be null/undefined: 
let result = data ? (data.key1 ? data.key1.key2 : undefined) : undefined; 
// Another equivalent alternative: 
let result = ((data || {}).key1 || {}).key2;

Nasty! This gets much much worse if you need to go deeper, and although the second example works at runtime, it won't even compile in TypeScript, since the first step could be {}, in which case key1 isn't a valid key at all.

This gets still more complicated if you're trying to get into an array, or there's a function call somewhere in this process.

There's a host of other approaches to this, but they're all noisy, messy & error-prone. With optional chaining, you can do this:

// With TS 3.7: 
// Returns the value is it's all defined & non-null, or undefined if not. 
let result = data?.key1?.key2; 
// The same, through an array index or property, if possible: 
array?.[0]?.['key']; 
// Call a method, but only if it's defined: 
obj.method?.(); 
// Get a property, or return 'default' if any step is not defined: 
let result = data?.key1?.key2 ?? 'default';

The last case shows how neatly some of these dovetails together: null coalescing + optional chaining is a match made in heaven.

One gotcha: this will return undefined for missing values, even if they were null, e.g. in cases like (null)?.key (returns undefined). A small point, but one to watch out for if you have a lot of null in your data structures.

That's the lot! That should outline all the essentials for these features, but there are lots of smaller improvements, fixes, and editor support improvements coming too, so take a look at the official roadmap if you want to get into the nitty-gritty.

Introduction Boolean in JavaScript and TypeScript

Introduction Boolean in JavaScript and TypeScript

Boolean values are supported by both JavaScript and TypeScript and stored as true/false values .This is because, while JavaScript coerces an object to its primitive type, the TypeScript type system does not. TypeScript treats it like an object type.

Boolean in JavaScript

boolean can take the values of true and false. Values from other types can be truthy or falsy, like undefined or null.

let b = true
if(b) console.log('logged')

b = false
if(b) console.log('not logged')

b = undefined
if(b) console.log('not logged')

b = null
if(b) console.log('not logged')

Values other than undefined, null or false considered falsy are "" (empty string), -0 and 0, as well as NaN.

To get the boolean value of any value, you can use the Boolean function:

Boolean(false) // false
Boolean(true) // true
Boolean("false") // true โ—๏ธ
Boolean("Hey folks") // true
Boolean({}) // true
Boolean([]) // true
Boolean(123.4) // true
Boolean(Symbol()) // true
Boolean(function() {}) // true
Boolean(undefined) // false
Boolean(null) // false
Boolean(NaN) // false
Boolean(0) // false
Boolean("") // false

Rule of thumb: All empty values evaluate to false. Empty object {} and empty array [] (which is an object itself) do have value as they are containers for other values.

The Boolean function is really good to filter empty values from collections:

const collection = [
  { name: 'Stefan Baumgartner', age: 37 },
  undefined,
  { name: 'D.', age: 36 },
  false
  { name: 'C.', age: 2},
  false
]

collection.filter(Boolean) // handy!

Together with Number โ€“ which converts all values into their number counterpart or NaN, this is a really cool way of getting to actual values quickly:

const x = ["1.23", 2137123, "wut", false, "lol", undefined, null]
  .map(Number)
  .filter(Boolean) // [1.23, 2137123] ๐Ÿ‘

Boolean exists as a constructor and has the same conversion rules as the Boolean function. However, with new Boolean(...) you create a wrapping object, making value comparisions truthy, but reference comparisions falsy:

const value = Boolean("Stefan") // true
const reference = new Boolean("Stefan") // [Boolean: true]

value == reference // true
value === reference // false

You get to the value via .valueOf():

value === reference.valueOf() // true

I have a REPL for you to check. The use of Boolean as a function is obviously great, but new Boolean has very limited use. If you know a practical use case, please let me know.

Boolean in TypeScript

boolean in TypeScript is a primitive type. Be sure to use the lower case version and donโ€™t refer to
object instances from Boolean

const boolLiteral: boolean = false // ๐Ÿ‘
const boolObject: Boolean = false // ๐Ÿ‘Ž

It works, but itโ€™s bad practice as we really rarely need new Boolean objects.

You can assign true, false and undefined and null to boolean in TypeScript without strict null checks.

const boolTrue: boolean = true // ๐Ÿ‘
const boolFalse: boolean = false // ๐Ÿ‘
const boolUndefined: boolean = undefined // ๐Ÿ‘
const boolNull: boolean = null // ๐Ÿ‘

With that, boolean is the only one we can express fully through union types:

type MyBoolean = true | false | null | undefined // same as boolean

const mybool: MyBoolean = true
const yourbool: boolean = false

When we enable the strictNullChecks compiler flag, the set of values reduces to true and false.

const boolTrue: boolean = true // ๐Ÿ‘
const boolFalse: boolean = false // ๐Ÿ‘
const boolUndefined: boolean = undefined // ๐Ÿ’ฅ
const boolNull: boolean = null // ๐Ÿ’ฅ

So our set reduces to two values in total.

type MyStrictBoolean = true | false

We can also get rid of null values with the NonNullable helper type:

type NonNullable<T> = T extends null | undefined
  ? never
  : T;

type MyStrictBoolean = NonNullable<MyBoolean> // true | false

The fact that boolean consists of a limited set of values only used in conditions, allows for interesting conditional types.

Think of an mutation in a datastore through a function. You set a flag in a function that updates e.g. the user id. You have to provide the user ID then:

type CheckUserId<Properties, AddUserId> = 
    AddUserId extends true 
    ? Properties & { userId: string }
    : Properties & { userId?: string }

Depending on the value of our generic AddUserId, we expect the property userId to be set or to be optional.

We can make this type more explicit by extending our generics from the types we expect

- type CheckUserId<Properties, AddUserId> = 
+ type CheckuserId<
+  Properties extends {},
+  AddUserId extends boolean
+ >
     AddUserId extends true 
     ? Properties & { userId: string }
     : Properties & { userId?: string }

In use, it might declare a function like this:

declare function mutate<P, A extends boolean = false>
  (props: CheckUserId<P, A>, addUserId?: A): void

Note that I even set a default value for A to make sure CheckUserId gives the correct info depending on addUserId to be set or not.

The function in action:

mutate({}) // ๐Ÿ‘
mutate({ data: 'Hello folks' }) // ๐Ÿ‘
mutate({ name: 'Stefan' }, false) // ๐Ÿ‘
mutate({ name: 'Stefan' }, true) // ๐Ÿ’ฅ userId is missing
mutate({ name: 'Stefan', userId: 'asdf' }, true) // ๐Ÿ‘ userId is here

Handy if your code relies a lot on truthy and falsy values. As always, thereโ€™s playground for you.

Originally published at fettblog.eu on 10 September 2019

Understanding void in JavaScript and TypeScript

Understanding void in JavaScript and TypeScript

void exists in both JavaScript as an operator and in TypeScript as a primitive type. And in both worlds void works a little bit different than most people are used to.

If you come from traditional, strongly typed languages you might be familiar with the concept of void: A type telling you that functions and methods return nothing when called.

void in JavaScript

void in JavaScript is an operator which evaluates the expression next to it. No matter which expression is evaluated, void always returns undefined.

let i = void 2; // i === undefined

Why would we need something like this? First, in earlier times, people were able to override undefined and giving it an actual value. void always returned the real undefined.

Second, itโ€™s a nice way to call immediately invoked functions:

void function() {
  console.log('What')
}()

All without polluting the global namespace:

void function aRecursion(i) {
  if(i > 0) {
    console.log(i--)
    aRecursion(i)
  }
}(3)

console.log(typeof aRecursion) // undefined

Since void always returns undefined, and void always evaluates the expression next to it, you have a very terse way of returning from a function without returning a value, but still calling a callback for example:

// returning something else than undefined would crash the app
function middleware(nextCallback) {
  if(conditionApplies()) {
    return void nextCallback();
  }
}

Which brings me to the most important use case of void: Itโ€™s a security gate for your app. When your function is always supposed to return undefined, you can make sure that this is always the case.

button.onclick = () => void doSomething();

void in TypeScript

void in TypeScript is a subtype of undefined. Functions in JavaScript always return something. Either itโ€™s a value, or undefined

function iHaveNoReturnValue(i) {
  console.log(i)
} // returns undefined

Since functions without a return value always return undefined, and void always returns undefined in JavaScript, void in TypeScript is a proper type for telling developers that this function returns undefined:

declare function iHaveNoReturnValue(i: number): void

void as type can also be used for parameters and all other declarations. The only value that can be passed is undefined:

declare function iTakeNoParameters(x: void): void

iTakeNoParameters() // ๐Ÿ‘
iTakeNoParameters(undefined) // ๐Ÿ‘
iTakeNoParameters(void 2) // ๐Ÿ‘

So void and undefined are pretty much the same. Thereโ€™s one little difference though, and this difference is significant: void as a return type can be substituted with different types, to allow for advanced callback patterns:

function doSomething(callback: () => void) {
  let c = callback() // at this position, callback always returns undefined
  //c is also of type undefiend
}

// this function returns a number
function aNumberCallback(): number {
  return 2;
}

// works ๐Ÿ‘ type safety is ensured in doSometing
doSomething(aNumberCallback) 

This is desired behaviour and often used in JavaScript applications. Read more on this pattern called substitutability in my other articles.

If you want to make sure to pass functions who only return undefined (as in โ€œnothingโ€), be sure to adapt your callback method signature:

- function doSomething(callback: () => void) {
+ function doSomething(callback: () => undefined) { /* ... */ }

function aNumberCallback(): number { return 2; }

// ๐Ÿ’ฅ types don't match
doSomething(aNumberCallback)

Youโ€™ll propably be good with void most of the time.

Originally published at fettblog.eu on 06 September 2019

JavaScript vs Typescript: What's the Difference?

JavaScript vs Typescript: What's the Difference?

For a Developer, It's very important to decide which language he should use to develop an application with a specific requirement. In this post, you'll see the difference between JavaScript and Typescript, from which you choose the language that's right for you.

Originally published at https://www.guru99.com/
JavaScript vs Typescript: What's the Difference?

In this tutorial, you will learn

  • What is JavaScript?
  • What is Typescript?
  • Why JavaScript?
  • Why Typescript?
  • History of Javascript
  • History of Typescript
  • Features of Javascript
  • Features of Typescript
  • Typescript vs. JavaScript
  • What is better?
What is JavaScript?

JavaScript is a scripting language which helps you create interactive web pages. It followed rules of client-side programming, so it runs in the user's web browser without the need of any resources forms the web server. You can also use Javascript with other technologies like REST APIs, XML, and more.

The idea behind developing this script is to make it a complementary scripting language like Visual Basic was to C++ in Microsoft's language families. However, JavaScript is not designed for large complex applications. It was developed for applications with a few hundred lines of code!

What is Typescript?

Typescript is a modern age Javascript development language. It is a statically compiled language to write clear and simple Javascript code. It can be run on Node js or any browser which supports ECMAScript 3 or newer versions.

Typescript provides optional static typing, classes, and interface. For a large JavaScript project adopting Typescript can bring you more robust software and easily deployable with a regular JavaScript application.ย 

Why JavaScript?
  • Open source project with Microsoft's patronage
  • Specially designed tool for small scripts
  • Supports classes, interfaces & modules.
  • Compiled JavaScript runs in any browser
  • Allows cross-compilation
  • You can extend JavaScript for writing large apps
  • Adds support for classes, interfaces, and modules
Why Typescript?
  • TypeScript supports JS libraries & API Documentation
  • It is a superset of Javascript
  • It is optionally typed scripting language
  • TypeScript Code can be converted into plain JavaScript Code
  • Better code structuring and object-oriented programming techniques
  • Allows better development time tool support
  • It can extend the language beyond the standard decorators, async/await
History of Javascript

Netscape Communications Corporation programmer Brendan Eich created Javascript. It was meant to working Netscape navigator. However, after becoming a popular scripting tool, it is had become LiveScript. Later on, it was renamed as JavaScript to reflect Netscape's support of Java within its browser.

Let see an important landmark in the history of Javascript:

  • It was launched in September 1995, and It took just ten days to develop this e scripting language which was initially called Mocha
  • In November 1996, Netscape submitted JavaScript to ECMA (European Computer Manufacturers Association) International
  • ECMAScript 2 was released in 1998
  • ECMAScript 3 was released in 1999
  • In 2005, Eich and Mozilla join ECMA to develop E4X Java script
  • In January 2009, the CommonJS project was launched with the aim of defining a common standard library
  • In June 2011, ECMAScript 5.1 was released
  • In June 2015. ECMAScript 2016 was released
  • The current version is ECMAScript 2017 which was released in June 2017
History of Typescript

Let see important landmarks from the History of Typescript:

  • The typescript was first made public in the year 2012
  • After two years of internal development at Microsoft. TypeScript 0.9, released in 2013
  • Additional support for generics TypeScript 1.0 was released at Build 2014
  • In July 2014, a new TypeScript compiler came which is five times faster then it's previous version
  • In July 2015, support for ES6 modules, namespace keyword, for, of support, decorators
  • In November 2016, an added feature like key and lookup types mapped types, and rest
  • On March 27, 2018, conditional types, the improved key with intersection types supports added in the Typescript.
Features of Javascript
  • It's a cross-platform language
  • It's used for client side and server side
  • It's easy to learn and to start with
  • It's a dynamic language: flexible and powerful
  • You have 'the great freedom' to do whatever you want with any object
  • Strong Testing Workflow
  • Added Dependencies
  • Framework Unsupported
Features of Typescript
  • Maintainability
  • Offered great productivity for developers
  • Code navigation and bug prevention
  • Code 'discoverability' & refactoring
  • Optional Static Type Annotation / Static Typing
  • Additional Features for Functions
  • Supports ES6
  • Supports interfaces, sub-interfaces, classes, and subclasses
  • Scalable HTML5 client-side development
  • Rich IDE available with autocomplete and code navigation features.
  • Class-based object-oriented with the inheritance of private members and interfaces.
JavaScript vs Typescript

What is better?

In the end, we can say that if an experienced developer is working on relatively small coding projects, then JavaScript is ideal. However, if you have knowledge and expertise development team, then Typescript is a most preferred option.ย 

Summary
  • JavaScript is a scripting language which helps you create interactive web pages
  • Typescript is a modern age Javascript development language
  • Javascript is a specially designed tool for small scripts
  • TypeScript supports JS libraries & API Documentation
  • Javascript first version was published in the year 1995
  • The typescript was first made public in the year 2012
  • It's used for client side and server side
  • Typescript offered great productivity for developers
  • Javascript is a Lightweight, interpreted, object-oriented language with first-class functions
  • Typescript is a powerful type system, including generics & JS features
  • For small size project Javascript is an ideal option, but for large size project you can use Typescriptย 

Thanks for reading โค

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further readingย 

โ˜ž JavaScript Basics Before You Learn React

โ˜ž Build a CMS with Laravel and Vue

โ˜ž Googleโ€™s Go Essentials For Node.js / JavaScript Developers

โ˜ž From Javascript to Typescript to Elm

โ˜ž Creating a Modal Dialog in Angular 8 with TypeScript