An intro to Typescript 3.0’s ‘unknown’ type

Typescript 3.0 introduced the ‘unknown’ type. Anything is assignable to unknown but unknown isn’t assignable to anything. This is useful for the below situation.

const s: string = loadData()
let obj: unknown = JSON.parse(s)

As soon as you try and assign obj to anything or try to pass it into a function you will receive the below error.

index.ts:30:11 – error TS2345: Argument of type ‘unknown’ is not assignable to parameter of type ‘MyClass’.

This is contrast to the ‘any’ type which is pretty much anything goes, type safety be gone.

But what good is an object you can’t do anything with? That is where a type guard function comes in.

function isMyClass(obj: any): obj is MyClass {
if (obj.name === undefined || obj.kind === undefined) {
return false
}
return true
}

if (isMyClass(obj)) {
// within the if block obj’s type will now magically be MyClass
console.log(obj.name)
}

Now you have extremely strict type checking when dealing with strings received from an API, database or wherever and your type guard will act as a gatekeeper.