Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an 'object literal' in TypeScript?

Tags:

typescript

I see the term 'object literal' used a lot in TypeScript (eg see this answer) - what do we actually mean by 'object literal' and how is it different just an 'object'?

Here's some relevant documentation in the official documentation:

Object types

In JavaScript, the fundamental way that we group and pass around data is through objects. In TypeScript, we represent those through object types.

Literal types

In addition to the general types string and number, we can refer to specific strings and numbers in type positions.

So I understand the concept of literal types, when we are referring to strings or numbers, where you're talking about narrower, specific value. eg "bob" rather than the wider string.

What exactly is an object literal?

like image 739
dwjohnston Avatar asked Oct 25 '25 09:10

dwjohnston


2 Answers

An object literal is when you use curly brackets to create an object, as in:

const example = { hello: "world" };

That's in comparison to creating an instance of a class, as in:

const now = new Date();

(Note: object literals exist in plain javascript too, not just typescript)

like image 97
Nicholas Tower Avatar answered Oct 28 '25 01:10

Nicholas Tower


The TypeScript handbook indeed doesn't explain this, but it's very simple. It's basically whenever you use the JS object notation syntax ({ ... }) to create an object. TypeScript sees that as an object literal, which gets some extra type checking.

When you use an object literal for a type, it'll actually check whether your literal contains keys that don't exist in the target type. Usually this type checking is glanced over (e.g. you can assign an Apple to a Fruit variable). Object literals get actually checked during creation. There are also some other special interactions when using object literals for generic parameters.

like image 29
Kelvin Schoofs Avatar answered Oct 27 '25 23:10

Kelvin Schoofs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!