Last updated: Feb 28, 2024
Reading timeยท2 min
Use a user-defined type guard to check if a value with unknown
type contains
a property in TypeScript.
The user-defined type guard consists of a function that checks if the specific property is contained in the object and returns a predicate.
interface Person { name: string; age: string; } function isPerson(obj: unknown): obj is Person { return ( typeof obj === 'object' && obj !== null && 'name' in obj && 'age' in obj ); } const obj: unknown = { name: 'Bobby Hadz', age: 30, }; if (isPerson(obj)) { console.log(obj.name); // ๐๏ธ "Bobby Hadz" console.log(obj.age); // ๐๏ธ 30 }
We used a
user-defined type guard
to check if an object contains the name
and age
properties.
obj is Person
syntax is a type predicate where obj
must be the name of the parameter the function takes.We first check if the passed-in value has a
type of
object
.
Unfortunately, we also have to
check that the object isn't equal to null
because null
has a type of object in JavaScript (and TypeScript).
console.log(typeof null); // ๐๏ธ "object"
At this point, we can use the
in operator
to check if the name
and age
properties are contained in the object.
const obj = { name: 'Bobby Hadz', age: 29, }; console.log('name' in obj); // ๐๏ธ true console.log('age' in obj); // ๐๏ธ true console.log('test' in obj); // ๐๏ธ false
The in
operator checks if a specific property is contained in the object or
its prototype chain and returns a boolean result - true
if it is and false
otherwise.
User-defined type guards are useful in this situation because in the if
block
TypeScript types the object to be of the specified type.
interface Person { name: string; age: string; } function isPerson(obj: unknown): obj is Person { return ( typeof obj === 'object' && obj !== null && 'name' in obj && 'age' in obj ); } const obj: unknown = { name: 'Bobby Hadz', age: 30, }; if (isPerson(obj)) { // ๐๏ธ obj is of type Person here console.log(obj.name); // ๐๏ธ "Bobby Hadz" console.log(obj.age); // ๐๏ธ 30 }
Once we are in the if
block, TypeScript knows the obj
variable has a type of
Person
and allows us to access all of the properties a Person
has.
If you get the error that Object is of type 'unknown', click on the link and follow the instructions.
You can learn more about the related topics by checking out the following tutorials: