Perbezaan Antara &#Objek&#, &#{}&#, dan 'objek' dalam TypeScript

王林
Lepaskan: 2024-07-24 15:52:30
asal
998 人浏览过

In TypeScript, when we want to define an object type, there are several concise options such as 'Object', '{}', and 'object'. What are the differences between them?

Object (uppercased)

Object (uppercased) describes properties common to all JavaScipt objects. It is defined in the lib.es5.d.ts file that comes with the TypeScript library.

The Differences Between

As you can see, it includes some common properties like toString(), valueOf(), and so on.

Because it emphasizes only those properties that are common to JavaScript objects. So you can assign boxable objects like string, boolean, number, bigint, symbol to it, but not the other way around.

The Differences Between

{}

{} describes an object that has no members of its own, which means TypeScript will complain if you try to access its property members:

The Differences Between

From the code example above, we can see that {} and Object (uppercased) have the same features. That is, it can only access those properties that are common (even if the JavaScript code logic is correct), all boxable objects can be assigned to it, etc.

This is because the {} type can access those common properties through the prototype chain, and it also has no own properties. So it behaves the same as the Object (uppercased) type. But they represent different concepts.

object (lowercased)

object (lowercased) means any non-primitive type, which is expressed in code like this:

type PrimitiveType =
  | undefined
  | null
  | string
  | number
  | boolean
  | bigint
  | symbol;

type NonPrimitiveType = object;
Salin selepas log masuk

This means that all non-primitive types are not assignable to it, and vice versa.

The Differences Between

Snack: Record

In the source code of many common libraries, we may see Record to represent non-primitive types. It has the same effect as object (lowercased), but it is more semantic.


If you find my content helpful, please consider subscribing. I send a _ weekly newsletter every Sunday _ with the latest web development updates. Thanks for your support!

以上是Perbezaan Antara &#Objek&#, &#{}&#, dan 'objek' dalam TypeScript的详细内容。更多信息请关注PHP中文网其他相关文章!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!