Typescript - Tips & Tricks - typeof

February 15, 2021

Last updated: September 9, 2021

392 words

Post contents

Today I want to start a series of tips and tricks about Typescript. I will try to publish two/three tips & tricks a week. Before start, I want to explain why I start this series. I start this series because every day I see too many any types in the typescript files and so I want to help the developers to learn better the typescript language.

typeof

Today I start with the typeof operator. Typeof is an operator used to detect the type of our variables. A little preamble, typeof is also a javascript operator, but with typescript, it has superpowers.

Typeof in javascript has these behaviors:

const valueString = "string";const valueNumber = 1;const valueBoolean = true;const valueBigInt = 1n;const valueFunction = () => true;const valueUndefined = undefined;const valueNull = null;const object = {  prop1: "value1",  prop2: "value2",};console.log(typeof valueString); // stringconsole.log(typeof valueNumber); // numberconsole.log(typeof valueBoolean); // booleanconsole.log(typeof valueBigInt); // bigintconsole.log(typeof valueFunction); // functionconsole.log(typeof valueUndefined); // undefinedconsole.log(typeof valueNull); // objectconsole.log(typeof object); // object

How we can see some things are strange: e.g. when we get the typeof of a null variable javascript returns an object type.

But here we see the same example in typescript:

type valueStringType = typeof valueString; // "string"type valueNumberType = typeof valueNumber; // 1type valueBooleanType = typeof valueBoolean; // truetype valueBigIntType = typeof valueBigInt; // 1ntype valueFunctionType = typeof valueFunction; // () => booleantype valueUndefinedType = typeof valueUndefined; // undefinedtype valueNullType = typeof valueNull; // nulltype objectType = typeof object; // { prop1: string; prop2: string; }

The first impact is friendlier for us developers because the typeof operator converts the type exactly as expected. The best advantages can be seen in the types: function, null, object.

But now an advanced example:

const item = {  id: '0000',  name: 'Item',  unit: {    id: '1',    code: 'PZ'  },  variants: [{    id: '1',    code: '001',    color: 'FFFFFF'  }]};type Item = typeof item;type Unit = typeof item["unit"];type Variant = typeof item.variants[number];

In this example, we can see how we can extract simple types from a complex object.

I leave you the link of the official documentation of this operator.

For today is all. See you soon!

Subscribe to our newsletter!

Subscribe to our newsletter to get updates on new content we create, events we have coming up, and more! We'll make sure not to spam you and provide good insights to the content we have.