I haven't encountered any type warnings in the places where I anticipated them

When I define an object like this:

const x: { str: string, num: number } = {
    str: str,
    num: not_a_num
  };

I am surprised to find that even though 'not_a_num' is a string and not a number, the compiler does not throw an error. Instead, it creates an object with two string properties.

Furthermore, I have a function declared as:

store(array: Array<{ str: string, num: number }>): Promise<any> { //... }

But when I pass an array containing the object 'x' as a parameter, typeof(array[0].num) resolves to "string", which is unexpected given my type annotations.

My question is: Why am I not receiving any compiler warnings or errors in these cases? What's the purpose of using type annotations if they don't catch incorrect data types being passed in?

Thank you for your help!

Answer №1

The issue here arises from the fact that not_a_num is declared as type any. In TypeScript, using any means it can be any other type, leading to potential compatibility issues.

let str = "";
let not_a_num:any = "";

const xWithAny: { str: string, num: any } = {
    str: str,
    num: not_a_num
};
const x: { str: string, num: number }  = xx; // this assignment is valid

Type compatibility in TypeScript is determined by the individual components, hence xWithAny is compatible with x because their str properties have matching types and num:any can be assigned to num:number.

The main issue arises during runtime where not_a_num being of type any can take on any value, potentially causing num to end up as a string instead of a number.

It's generally recommended to avoid using any unless necessary, and if used, one should consciously consider why they are opting for any. Enabling noImplicitAny flag in the TypeScript compiler can provide some assistance in managing this issue.

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

What is causing the failure of this polymorphic assignment within a typed observableArray in Knockout?

Consider a scenario where we have a class A and its subclass B. The goal is to assign an array of instances of class B to an array of instances of class A. While this works with normal arrays, the same operation fails when using ko.ObservableArray. import ...

What is the process of destructuring an array containing objects?

Examining this JSON structure: { "Person": { "UID": 78, "Name": "Brampage", "Surname": "Foo" }, "Notes": [ { "UID": 78, "DateTime": "2017-03-15T15:43:04.4072317", "Person": { ...

Is it necessary to use Generics in order for a TypeScript `extends` conditional type statement to function properly?

Looking to improve my understanding of the extends keyword in TypeScript and its various uses. I recently discovered two built-in utilities, Extract and Exclude, which utilize both extends and Conditional Typing. /** * Exclude from T those types that are ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

In TypeScript, the 'onChange' is declared multiple times, therefore this particular usage will be scrutinized carefully

Within my React project, I am utilizing material-ui, react-hook-form, and Typescript. However, I encountered an error in VSCode when attempting to add the onChange function to a TextField component: 'onChange' is specified more than once, resul ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

Building a versatile component library for Next.js using TypeScript and Tailwind CSS: Step-by-step guide

Lately, I've been utilizing Next.js and crafting components such as buttons, inputs, and cards with Tailwind CSS for my various projects. However, the repetitive task of rewriting these components from scratch for each new project has become quite tir ...

Transformation of Ionic 2 ScreenOrientation Plugin

Can someone assist me with this issue? A while back, my Ionic 2 app was functioning correctly using the ScreenOrientation Cordova plugin and the following code: window.addEventListener('orientationchange', ()=>{ console.info('DEVICE OR ...

How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met: 1. Only allow uploading of zip files; display an error message for other file types 2. Restrict the file s ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

What is the best way to utilize the typescript module for detecting and managing typescript errors and warnings in your code?

Currently, I am experimenting with the typescript module to programmatically detect typescript errors. Below is a simplified version of what I have been working on: var ts=require('typescript') var file_content=` interface Message{ a:string ...

Some files are missing when performing an npm install for a local package

My project is structured like this: ├── functions/ │ ├── src │ ├── lib │ ├── package.json ├── shared/ │ ├── src │ | ├── index.ts | | ├── interfaces.ts | | └── validator_cl ...

What is the process to activate a function within a component once a service method has been run?

I'm currently working on a chart configuration using amCharts, where an eventListener is registered for the bullets. This event listener then triggers another function in my chart service. My goal is to activate a method in my component as soon as th ...

Sending binary information from a .net core web api to a typescript application

I currently have a .net core 3.0 web api application connected to an angular 8 client. While I have successfully transferred data between them using json serialization, I am now looking for a way to transfer a bytes array from the api to the client. After ...