简体   繁体   中英

How do I access React State properties using TypeScript? Get property does not exist on type error

I have defined a type, I get the expected data from my API. However, when I try access a property I get error Property 'deployed' does not exist on type 'Service[]'. . I'm confused because deployed is a property?

Here is my type:

export interface Service {
    service: String,
    deployed: String,
    message: String[]
}

Here is API request:

import axios from 'axios';
import { apiBaseURL } from '../constants';
import { Service } from '../types'

export const getStatus = async () => {
    const { data: status } = await axios.get<Service[]>(`${apiBaseURL}/status`);
    return status;
}

Code with error:

import React from 'react';
import './App.css';
import { getStatus } from './services/status';
import { Service } from './types';

function App() {
  const [status, setStatus] = React.useState<Service[]>([]);
  
  React.useEffect(()  => {
    (async () => {
      const response = await getStatus();
      setStatus(response);
      console.log(status);
    })()
  // eslint-disable-next-line
  }, [])

  return (
    <div className="App">
      <header className="App-header">
      <h1>App</h1>
      </header>
      {status && (
        <p>{status.deployed}</p>
      )}
    </div>
  );
}

export default App;

Service[] is an array. The array type does not have a property called deployed

This line:

  const [status, setStatus] = React.useState<Service[]>([]);

Says, status is a an array of Service .

This line:

        <p>{status.deployed}</p>

Says, you want access deployed method of that array. Which is wrong.

A possible way to check whether this hypothesis is right, would be to try to access deployed on an element of that array.

For example, assuming you have validated that there exists at least one element in status array, this:

        <p>{status[0].deployed}</p>

or if you wanted to print all the deployed status, something like this:

        {!!status && status.map(s => <p key={s.service}>{s.deployed}</p>)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM