Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Unknown is coming to TypeScript 3.0

If you use typescript, you must have come across the all-powerful any type. While it can encompass all possible types, it also makes TypeScript skip any type checking on it. This is great for some use cases where you are not sure about the structure of the object but want to access properties on it. But at times, it could also be a bit lax. Consider the following example:

function greet(person: any) {  
  person.name.greet();
  person.y.prop;
  person();
  new person();
}

In this case, TypeScript won't do any type checking which could result to runtime errors if the type of person doesn't have an expected type structure. This is where the new unknown type comes to the rescue. unknown signals to TypeScript that we don't know the type of object yet, but it doesn't skip any type checking. In other words, it is the least capable type in TypeScript. This means that we can still call person.name.greet on the person object, but we need to convince TypeScript compiler that person.name.greet is a function.
For each of the above use cases, here is how we can convince typescript of our usage:

if (  
  !!person 
  && typeof person === 'object' 
  && 'name' in person
  && typeof person.name.greet === 'function') {
  person.name.greet();
}

if (!!person  
  && typeof person === 'function') {
  person();
  new person();
}

Want to know what else is coming in Typescript 3.0? Check out the official release post.