Skip to main content

TypeScript Magic: Leveraging typeof

TypeScript, a statically typed superset of JavaScript, brings along powerful capabilities for object-oriented programming, one of which is inheritance.

––– views

Introduction

TypeScript, a statically typed superset of JavaScript, is renowned for enhancing code reliability, maintainability, and developer productivity. One of the remarkable features it provides is the typeof operator. This tool is used to fetch the type of a variable or, to be more precise, the type of the value carried by the variable.

Type Inference

Consider an array of complex objects, each possessing diverse properties like string, number, boolean, null, and other {} types. By using typeof combined with number in the format typeof array[number], we can swiftly gain insights into the structure of the array items. TypeScript will infer the full type of the object and represent it neatly.


_10
const data = [
_10
{
_10
foo: 'foo',
_10
bar: 'bar',
_10
count: 100,
_10
// more properties...
_10
},
_10
]
_10
_10
type ItemType = (typeof data)[number]