Exploring the Powers of Typescript Interfaces within Interfaces

Can you assist me with implementing an interface wrapped within a second interface? Here is the code snippet for the reducer:

import { createSlice } from '@reduxjs/toolkit';

export interface IStep {
  id: number;
  label: string;
  value: string;
  placeholder: string;
}

export interface InitialState {
  activeStep: number;
  steps: IStep[];
}

const initialState: InitialState = {
  activeStep: 0,
  steps: [
    {
      id: 0,
      label: 'First Name',
      value: '',
      placeholder: 'First Name',
    },
   ......
  ],
};

export const slice = createSlice({
  name: 'multiStepForm',
  initialState,
  reducers: {
   ......
  },
});

I want to use the InitialState interface in my Step component, which currently looks like this:

import React from 'react';
import { IStep } from 'redux/reducers/multiStepForm';

interface IPropsStep {
  activeStep: number;
  steps: IStep[];
  handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

const Step = ({ activeStep, steps, handleChange }: IPropsStep): JSX.Element => {
  return (
    <input
      id={steps[activeStep].id}
      type="text"
      onChange={handleChange}
      placeholder={steps[activeStep].placeholder}
      value={steps[activeStep].value}
    />
  );
};

export default Step;

It's evident that activeStep and steps are part of InitialState, but I'm unsure how to incorporate them.

I've attempted to do it as follows:

interface IPropsStep extends InitialState {
  handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}

const Step = ({ handleChange }: IPropsStep): JSX.Element => {
  return (
    <input
      id={steps[activeStep].id}
      type="text"
      onChange={handleChange}
      placeholder={steps[activeStep].placeholder}
      value={steps[activeStep].value}
    />
  );
};

However, I'm encountering errors because steps and activeStep are unknown in this context. How can I resolve this issue?

Answer №1

From what I gather from your query, it seems that accessing keys from an interface can be done in a similar manner as with an object.

interface UserData {
  username: UserDetails['username'];
  email: UserDetails['email'];
  updateUser: (data: UserDetails) => void;
}

This allows for direct reference to the UserDetails interface.

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

Having trouble directing my attention towards a Mat card when using viewchildren in Angular

My current challenge is trying to focus on a specific card from a list of mat cards Despite my efforts, I keep encountering an error that reads: Cannot read property 'focus' of undefined Access the code on StackBlitz The desired functionali ...

Creating a custom class to extend the Express.Session interface in TypeScript

I'm currently tackling a Typescript project that involves using npm packages. I am aiming to enhance the Express.Session interface with a new property. Here is an example Class: class Person { name: string; email: string; password: strin ...

Is it possible to utilize useRef to transfer a reference of an element to a child component?

When I want to mount something into the element with id tgmlviewer, I call it a viewer object. This process works smoothly when there is only one component of this kind. import React, { useEffect } from "react"; import { Viewer } from "../.. ...

A versatile generic type infused with dynamic typing and optional parameter flexibility

Looking to develop a function that can accept an optional errorCallback parameter. In cases where the consumer of this function does not provide a callback, I aim to default to a preset handler. The key criteria here are strong typing and utilizing the ret ...

What are the steps to integrate jQuery into an Angular 8 application?

I am currently working on an application that relies on SignalR for communication with a desktop application. In order to make use of SignalR, I include jQuery in my .ts file. However, after migrating from Angular 7 to Angular 8, it appears that this setup ...

The compatibility issue arises when using Material UI Portal with TypeScript, specifically with the 'children' property types

When rendering a component using Material-UI Portal that includes several Material UI buttons, the following code is used: <Portal container={this.myContainer}> <Button onClick={this.handleClick}>Do something</Button> //other but ...

What steps should I take to ensure that this test covers all possible scenarios?

I recently started learning React development and am currently exploring testing with Jest and React Testing Library (RTL). However, I'm facing challenges in achieving complete test coverage for the component code below: import { CustomCardActions, ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

Applying specific data types to object properties for precise value identification in Typescript

I've been working on creating a dynamic settings menu in TypeScript using the following data: const userSettings = { testToggle: { title: "Toggle me", type: "toggle", value: false, }, testDropdow ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...

Having trouble changing file names in a Next.js 13 project

I've been facing an issue ever since Next.Js 13 updated the `pages` folder to a new `app` folder. Whenever I try to rename the default "Pages.tsx" file to something like "Home.tsx" or "Information.tsx", it breaks and shows a 404 Page error. The first ...

Is there a way to handle null return in case the data is not present?

Is there a way to handle situations where the data I pass is empty, like if(!testimonials) return null? Currently, it just shows an empty array. I'm not sure where to implement an "if-else" rule. AboutUs Page export const getServerSideProps = async ( ...

Exploring TypeScript reflections within a specific namespace

(Building upon previous discussions about dynamically loading a TypeScript class) If I am currently within a namespace, is there a method to reference classes within the namespace in order to utilize 'reflection' to invoke their constructors? n ...

The Observer<T> generic type necessitates the specification of 1 type argument

I'm currently trying to grasp the concept of Observables in Angular 4. While watching a tutorial video on it, I attempted to create my first Observable but encountered an error in my IDE: The generic type Observer requires 1 types argument(s) Here ...

Using a function as a parameter in Typescript: Anticipated no arguments, received 1.ts

I'm encountering an issue when trying to pass the doSomething function into performAction. The error message I'm receiving is Expected 0 arguments, but got 1 interface SomeInterface { name: string, id: string } function doSomethingFunction( ...

The problem with the "typescript-react-apollo" codegen plugin is that it is declaring block-scope variables more than once in the generated

Recently, I embarked on a new project utilizing NextJS with graphql-codegen to auto-generate my apollo-react types from the API. Unfortunately, it seems to be generating duplicate exported variables right from the start, causing a typescript error and hi ...

Unable to activate ngx-scrollbar RTL mode in my Angular application

I have been working on implementing Right-to-Left (RTL) support for scrolling using the ngx-scrollbar package in my Angular project. Unfortunately, I am facing an issue where the scrollbar does not seem to function correctly when in RTL mode. To add ngx-s ...

Having difficulty transferring types to and from a custom module?

I'm currently faced with an issue while working on a typescript module within a larger monorepo. I am having difficulty importing types from one package into another via node modules. The types are located at ./types, and my package.json contains a ke ...

Executing functions in Vue TypeScript during initialization, creation, or mounting stages

Just a few hours ago, I kicked off my Vue TypeScript project. I've successfully configured eslint and tslint rules to format the code as desired, which has left me quite pleased. Now, I'm curious about how to utilize the created/mounted lifecycl ...