-2

Related to:

Specify return type in TypeScript arrow function

Why am I getting an error "Object literal may only specify known properties"?

In:

hooks/Test.tsx:

import { useState, useEffect } from 'react'

interface GeoLocationData {
    isGeoLocationDataSet: boolean
    lat: string
    lon: string
    errorCode: number,
    errorMsg: string
}

export const Test = (): GeoLocationData => {
    const [geoLocationData, setGeolocationData] = useState<GeoLocationData>({
        isGeoLocationDataSet: false,
        lat: '',
        lon: '',
        errorCode: 0,
        errorMsg: ''
    });

    // stuff here
    return geoLocationData
}

geoLocationData is not cast to type GeoLocationData when used in another component:

import React from 'react';
import './App.css';
import { Test} from './hooks/Test';

function App() {
  const geoLocation = Test
  return (
    <div className="App">
      <body className="App-body">
        <p>
          {geoLocation.isGeoLocationDataSet
            ? JSON.stringify(geoLocation)
            : "No"}
        </p>
      </body>
    </div>
  );
}

export default App;

err:

Property 'isGeoLocationDataSet' does not exist on type '() => GeoLocationData'.ts(2339)

But isGeoLocationDataSetdoes exist as a prop in GeoLocationData.

The following ():

export const Test = (): GeoLocationData => ({
    const [geoLocationData, setGeolocationData] = useState<GeoLocationData>({
        isGeoLocationDataSet: false,
        lat: '',
        lon: '',
        errorCode: 0,
        errorMsg: ''
    });

    // stuff here
    return geoLocationData
})

produces:

Type '{ const: [GeoLocationData, React.Dispatch<React.SetStateAction<GeoLocationData>>]; return: any; }' is not assignable to type 'GeoLocationData'.
  Object literal may only specify known properties, and 'const' does not exist in type 'GeoLocationData'.

but return is still an.

Sebi
  • 4,262
  • 13
  • 60
  • 116

1 Answers1

2

Test is a function, so you need to call it to get the returned value of type GeoLocationData:

const geoLocation = Test();
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48