How come a number can be assigned to an Object reference in TypeScript?

Is TypeScript bending the rules?

var x: number = 5
var y: Object = x

It seems strange that a number is being assigned to an Object. Maybe x is being automatically converted to an object, but a simple check reveals otherwise:

if (!(y instanceof Object)) {
   console.log(typeof y)
}

This code snippet will print:

number

Just to clarify:

$ tsc --version
Version 1.8.10

Answer №1

When it comes to type compatibility in TypeScript, it follows a structural subtyping approach rather than nominal typing. To illustrate this point, consider the following interface definitions:

interface IFoo { X: number }
interface IBar { X: number; Y: number }

Does IBar extend IFoo? Not quite.

However, is IFoo compatible with IBar? Indeed it is.

The members of IFoo form a subset of IBar members, allowing for the assignment of any IBar to IFoo. The reverse operation is not possible:

var x: IFoo;
var y: IBar;

x = y // perfectly valid
y = x // results in a type error due to missing Y member in x

In TypeScript, all types can be considered compatible with Object, akin to treating it as an empty interface. This feature enables smooth interaction with JavaScript libraries by passing any valid TypeScript value to functions accepting Object.

I recommend delving into the details of Type Compatibility explained in the documentation, particularly focusing on the distinction between Subtype vs Assignment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to ensure Angular mat-button-toggle elements are perfectly aligned within their respective groups

https://i.stack.imgur.com/Wjtn5.png Hello there, I'm trying to make the numbers in the first group match the style of the second group (noche, mañana...). I've set both the group and individual element width to 100%, but the numbers beyond 22 ...

Error: The route in "src/app/api/orders/route.ts" does not conform to the necessary types for a Next.js Route. The "default" export field is not recognized as a valid Route

I need to retrieve the orders from the database using Prisma based on the user's email (authenticated via Google Provider). Here is the repository - https://github.com/Jayesh-kahnani/Snatch Here is the API. // src/app/api/order/route.ts import { Next ...

Http provider not found in Angular 4 when using Rails 5 API

I recently completed a tutorial on Angular and Rails which I found here, but I am encountering difficulties in implementing it successfully. Currently, I am working with Angular version 4.2.4. [Error] ERROR Error: No provider for Http! injectionError — ...

Encountering a Jest error stating "Function is not defined" while attempting to instantiate a spy in TypeScript

I'm attempting to simulate Cloudwatch in AWS using Jest and typescript, but I'm encountering an issue when trying to create a spy for the Cloudwatch.getMetricStatistics() function. The relevant parts of the app code are as follows: import AWS, { ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

Executing a function when pressing tab and shifting simultaneously in Angular

I am struggling to trigger a method while tab switching and navigating. I currently have it set up using 'click', but this only works when clicking on any element within the tab. My goal is to have the method activate upon tab switch. If anyone h ...

Finding parameters in Angular 4

I am working on implementing a multilanguage feature in an Angular app and I need to establish the default language when the site loads. The two languages supported are Spanish and English, with Spanish being the default language. In order to achieve this, ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

What are the steps to defining a static constant within a TypeScript class?

What is the best way to define a TypeScript static constant within a class so that it can be accessed without initializing the class instance? Below is an example of my class structure: export class CallTree{ public static readonly active = 1; .. ...

I am in need of a customized 'container' template that will display MyComponent based on a specific condition known as 'externalCondition'. MyComponent includes the usage of a Form and formValidation functionalities

container.html <div ngIf="externalCondition"> <!--Initially this is false. Later became true --!> <my-component #MyComponentElem > </my-component> <button [disabled]= "!myComponentElemRef.myDetailsF ...

How to upload a TypeScript package to NPM for installation using both import and CDN methods

I am eager to publish my TypeScript project on NPM. I am currently using the TypeScript Compiler (tsc) to transpile the .ts files of my project into output .js file(s). To generate the output files, I simply use the tsc command. Here is my tsconfig.json: ...

Embracing Typescript promises over jQuery deferred for improved code efficiency and reliability

Currently, I have the following lines of code that utilize the JQueryDeferred object from the type definition class jquery.d.ts. My goal is to replace jQuery deferred with TypeScript promises. Here is the existing JQueryDeferred code: class A { privat ...

"Discovering the method to showcase a list of camera roll image file names in a React Native

When attempting to display a list of images from the user's camera roll, I utilized expo-media-library to fetch assets using MediaLibrary.getAssetsAsync(). Initially, I aimed to showcase a list of filenames as the datasource for the images. Below is m ...

A utility type in Typescript for managing default database schema values

I am currently exploring a method for incorporating default and virtual values in a database schema. The concept involves using a utility type to automatically convert a schema for insertion (props with defaults or generated by virtuals aren't necessa ...

Specialized type for extra restriction on enum matching

In my current project, I am dealing with two enums named SourceEnum and TargetEnum. Each enum has a corresponding function that is called with specific parameters based on the enum value. The expected parameter types are defined by the type mappings Source ...

Exploring the capabilities of argon2-browser in a cutting-edge setup with vite

After spending several hours attempting to implement the argon2-browser library in a Vue app with Vite, I have been encountering a persistent error. Despite following the documentation closely, I keep receiving the following message: This require call is ...

Error [ERR_ASSERTION]: Requested handler for GET /test is missing or undefined

I am currently facing an issue with the controller function in my TypeScript code. Although the handler function is present in the controller file, it is still giving me an error. export const test = { options:{ handler: (request, reply) => { ...

Angular2 CLI express server.ts encountered an unexpected import token

Starting an Angular2 project and setting up the server with express and Angular CLI version 1.0.0-beta.25.5 has been challenging for me. The file structure looks something like this: project root |-server |-server.ts |-src |-app When attempting to r ...