When using an object literal, ensure that you only include properties that are already known. The specified property does not exist in the type '

As I delve into React-Redux, I came across this example: https://redux-toolkit.js.org/usage/usage-with-typescript. I am following a step-by-step approach to build what I need. In a new file named infopieceSlice.ts, the following code was added:

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppThunk, RootState } from '../../store/store';

interface InfopieceState {
  content: string[];
}

const initialInfopieceState: InfopieceState = {
  content: [],
};

export const infopieceSlice = createSlice({
  name: 'infopiece',
  initialInfopieceState,
  reducers: {
    add: (InfopieceState, action: PayloadAction<string>) => {
      InfopieceState.content.push(action.payload);
    },

  },
});

In the /store/store.ts file:

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
import logger from 'redux-logger';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware()
    .concat(logger)
});

export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;
export type AppDispatch = typeof store.dispatch; 

The errors encountered were:

src/features/counter/infopieceSlice.ts:19:3 - error TS2345: Argument of type '{ name: 
string; initialInfopieceState: InfopieceState; reducers: { add: (InfopieceState: unknown,  
action: { payload: string; type: string; }) => void; }; }' is not assignable to parameter of 
type 'CreateSliceOptions<unknown, SliceCaseReducers<unknown>, string>'.
  Object literal may only specify known properties, and 'initialInfopieceState' does not   
exist in type 'CreateSliceOptions<unknown, SliceCaseReducers<unknown>, string>'.

19   initialInfopieceState,
     ~~~~~~~~~~~~~~~~~~~~~

src/features/counter/infopieceSlice.ts:22:7 - error TS2571: Object is of type 'unknown'.

22       InfopieceState.content.push(action.payload);

The code snippet for creating React app with Redux TypeScript template is as follows (suggested at: https://redux-toolkit.js.org/introduction/getting-started):

npx create-react-app my-app --template redux-typescript
:

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppThunk, RootState } from '../../store/store';

interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: state => {
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
});  

The goal is to define InfopieceState and infopieceSlice that handle string[] data types. How can the type issues be resolved?

Answer №1

When using the createSlice function, it is important to specify

initialState: initialInfopieceState
instead of just initialInfopieceState.

The key in this case is initialState, so if you only write initialInfopieceState, it is actually a shorthand for

initialInfopieceState: initialInfopieceState
, which will cause an error since initialInfopieceState as a standalone key does not exist.

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

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

The class variable cannot access the Angular Http response returned by the service

I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular&apo ...

What is the best approach to manage dynamic regex values for input types within ngFor loop?

In my project, I have an array of objects containing details for dynamically generating input fields. I have successfully implemented the dynamic input field generation based on the type received from an API. However, I am facing a challenge with matching ...

Error: Headers already sent to the client, cannot set new headers

I am currently working on creating a basic API using passport-jwt and passport-local-mongoose. I have successfully set up all the JWT functions and created routes for registering and signing in users. One of these routes is meant to handle a GET request in ...

The Angular 4 HTTP patch method is encountering difficulties when called in code but functions properly when tested using Post

My attempts to make a patch and post call to the server are failing as it never reaches the server. Interestingly, the same request works flawlessly in Postman, so I suspect there might be an issue with my code. Both my post and patch methods are essentia ...

Implementing Bottleneck to control the rate of API requests within a software tool

In TypeScript, I am developing an API wrapper with asynchronous code to abide by the rate limit of 1 request/second set by the particular API. My goal is to create a single instantiated API wrapper that enables access to different endpoints using objects. ...

Leverage the same JSDoc comment across multiple TypeScript interfaces

If I have the interfaces below: interface Foo { /** * A date string in the format `yyyy-MM-dd` */ archiveDate: string; } interface Bar { /** * A date string in the format `yyyy-MM-dd` */ publishDate: string; } The JSDoc descriptions f ...

When a user clicks on empty space in Angular 2, the page will automatically redirect

When I receive a response from the server, I want to redirect to another page. However, this process takes around 60 seconds, so in the meantime, I want to display a spinner. Once the response is received, I should be redirected to the new page. Sounds sim ...

The positioning of CSS arrows using the "top" attribute is not relative to the top of the page when using absolute values

I am currently working on positioning the arrow in the screenshot using TypeScript calculations. However, I am facing an issue where the position is being determined based on the top of the black popup instead of the top of the screen. From the top of the ...

Guide to Integrating BLK Theme into an Angular CLI Project

I've recently set up an Angular project using CLI and I am interested in integrating the BLK theme by Creative Tim into this project. However, the only available option from Creative Tim is to download a pre-existing project and build upon that framew ...

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

Generate dynamic property values based on calculations

I am facing a challenge with a form that I have designed. Could you guide me on how to dynamically update the value of the calculate field (contingency) whenever the user modifies the values of budget1 and budget2? I have attempted several approaches witho ...

Making Mat-Tab Table Headers Sticky in Angular

I'm facing an issue in my application where I have a screen with 3 tabs. One of these tabs contains a table with a large number of rows, and I want to make the headers of this table sticky so that they remain visible when the user scrolls down. Despit ...

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Node is experiencing difficulty incorporating the AWS DynamoDB package into the project

Important Note: Although AWS SAM and DynamoDB are mentioned here, this question is primarily related to the AWS JavaScript SDK, or potentially just a Node/NPM query at its core. It should be answerable by anyone experienced in developing Node/JavaScript ap ...

Could it be possible for a Firestore onUpdate trigger's change parameter, specifically change.after.data() and change.before.data(), to become null or undefined?

Presented below is a snippet of my cloud function exports.onUpdateEvent = functions.firestore.document('collection/{documentId}') .onUpdate((change, context) => { const after: FirebaseFirestore.DocumentData = change.after.data(); const ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Trouble with action creators not appearing in "this.props" while using redux-form version 6.0.0-rc.3

After updating redux-form from version 5.3.1 to 6.0.0-rc.3 for Material-UI integration, some changes were made: Fields removed from render(): const { handleSubmit, fields: { email, password, passwordConfirm }} = this.props; Errors validation removed f ...

What is the best way to retrieve an element from an array that was obtained via an http.get request?

Upon making an http get request in Angular, I received an array of Question objects. However, I am encountering an issue where I cannot access an element from it due to the error message: Cannot read property '0' of undefined. My assumption is th ...

Enhanced assistance for optional chaining operator available in Visual Studio Code

React Native 0.56 now supports the Optional Chaining Operator with ?. Unfortunately, the latest stable version of VS Code does not recognize this syntax and displays a TypeScript validation error: [ts] Expression expected. No compile-time or eslint erro ...