The type 'number | undefined' cannot be assigned to the type 'number'

const initialProgram =  {
    id: 0,
    studentId : 0,
    targets : []
}

const [program, setProgram] = useState(initialProgram);

In one of my functions I am updating the program as follows: setProgram({...program,studentId= selectedStudent?.id})

The type definition for selected Student is: selectedStudent: Student | undefined;

I need to make sure that selectedStudent remains unchanged.

How can I modify initialState to fix this error?

Answer №1

You have specified that the studentId property should hold a number.

selectedStudent?.id may be either a number or undefined.

Because undefined is not a number, an error occurs.

There are various ways to fix this error, but without more information, it is difficult to determine the best solution.

Check if the value is undefined and provide a default number

setProgram({
    ...program,
    studentId: selectedStudent?.id ?? 0
});

Alternatively, use an explicit type that allows the property to be undefined

type Program = {
    id: number;
    studentId?: number;
    targets: Something[]
}

const initialState: Program =  {
    id: 0,
    studentId : 0,
    targets : []
}

Answer №2

Handling the situation on the state side is crucial in determining the approach.

Based on the initialState, it can be deduced that studentId is expected to be a number. Since undefined is not a number, the error occurs when trying to assign selectedStudent?.id.

If you wish to default to 0 when selectedStudent is undefined, try the following alternative:

setProgram({...program, studentId= selectedStudent?.id ?? 0})

To define acceptable values for studentId in TypeScript, you can specify them as follows:

type StateType = {
    id: number,
    studentId?: number, // or number | undefined
    targets: string[] // assuming string array
}
const initialState: StateType =  {
    id: 0,
    studentId : 0,
    targets : []
}

Alternatively,

const initialState =  {
    id: 0,
    studentId : 0 as number | undefined,
    targets: []
}

Answer №3

let initialData : any =  {
    userId: 1,
    userName : 'John',
    items : []
}

const [data, setData] = useState(initialData);

This code snippet is functioning correctly.

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

Tips for creating a TypeScript-compatible redux state tree with static typing and immutability:

One remarkable feature of TypeScript + Redux is the ability to define a statically typed immutable state tree in the following manner: interface StateTree { readonly subState1: SubState1; readonly subState2: SubState2; ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

When you utilize useSelector, the state may be returned as undefined even after it has been initialized

In the process of developing a project that mirrors Twitter(X), my approach involves implementing state management with REDUX and maintaining persistent login using redux-persist. I am storing the user's username and token in both the Redux store (for ...

Locate and return the index in Typescript

Can you get the index of an element in an array using the array.find() method in TypeScript? For example, I know I can use find to retrieve an object based on a property value, but is it possible to also retrieve the index of that object in the array? ...

How can you verify if a variable is included in an HTTP response?

After successfully creating this authentication service, everything seemed to be running smoothly... import { HttpClient, HttpHeaders } from '@angular/common/http'; import { tap } from 'rxjs/operators'; import { Storage } from '@i ...

Leveraging cloud functions on Firebase for maximum efficiency

Question: Do you require a backend language when using Firebase Cloud Functions, or can TypeScript alone suffice for coding tasks like creating a matchmaking system? Response: There seems to be some uncertainty on the matter even from ChatGPT himself. Is ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

Is there a way to convert my messages into different languages without relying on the 'translate' directive or pipe?

Currently, my Angular application is set up with ngx-translate for translation purposes. While it is currently monolingual, I am already looking ahead to the possibility of needing to translate it in the future. Everything is functioning perfectly, but I w ...

The malfunction of Angular's tree component

After installing and importing the Angular tree component, I followed the basic example provided in order to set it up. However, upon following the steps outlined on , I encountered an issue where only the root node is visible without expanding. Could some ...

Selecting a GoJS Node using keys

In Angular with TypeScript, what is the best way to select a node from a diagram based on its key? Currently, I am required to left-click a newly created node in order to select it, but I would like for it to be automatically selected upon creation. I ha ...

Divide the enhanced document into sections using TypeScript

In my project, I am working with Material UI and TypeScript. I have noticed that I need to declare the Theme interface and ThemeOptions in the same file for it to work properly. Is there a more efficient way to separate these declarations from the main t ...

"Enhancing User Interfaces with Reactjs and Typescript: Exploring the Border

I am working on a component that takes borderStyle as a prop and then passes it down to a child div. I am trying to specify a type for this prop but I'm struggling to find the right one. Below is a snippet of my code that is relevant to this: inter ...

Include a query parameter each time a page is added to bookmarks

Is there a way to automatically add a query parameter to a page URL when bookmarked using Chrome? For example, if I bookmark https://www.example.com, can it be saved as https://www.example.com/?bookmarked? I'm thinking I might need to use JavaScript ...

What steps can be taken to prioritize files with specific extensions in webpack?

I have a dilemma with two files: - somefile.scss - somefile.scss.ts When importing the file in my typescript code, it is referencing the wrong one: import styles from "somefile.scss" The typescript part works fine with the correct import (.scss ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Identify and handle errors effectively using TypeScript

I have a question regarding my Express server setup. Here is the code snippet: import express from "express"; import helmet from "helmet"; import cors from "cors"; const app = express(); app.use(helmet()); app.use(cors()); a ...

Is there a way to establish a boundary for the forEach function in TypeScript?

In my web-based game, I use the forEach command to retrieve the team players in the lobby. However, for a specific feature in my game, I need to extract the id of the first player from the opposing team. How can I modify my current code to achieve this? T ...

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

Is there a way to disable the automatic refreshing of the useForm feature?

Upon clicking submit, all field information is supposed to be sent to the backend, but instead, it is being appended to the browser's URL. Furthermore, the error messages from yup are not being displayed. I attempted to use event.preventDefault in ha ...

Encountering NgRx Select Issues While Trying to Access Nested Properties

I've encountered TypeErrors while using NgRx select functions to access nested properties. In my app.module.ts, I have configured the root store as follows: StoreModule.forRoot({ app: appReducer }), The selectors causing errors are related to some ...