Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

React Native Functional Component useState Loses Typescript Class

$
0
0

I've got a functional component which has state with an object of a specific class:

import React from "react";import { ReactElement } from "react-native/node_modules/@types/react";import { useState } from "react";import { Text, View } from "react-native";import MyClass from "./MyClass";export default function FunCompWithState(): ReactElement {  const [myClass, setMyClass] = useState<MyClass>(new MyClass());  myClass.setTitle("New Title");  console.log("typeof:                " + typeof myClass);  console.log("object value:          " + myClass);  console.log("object variable title: " + myClass.getTitle());  console.log("object variable value: " + myClass.getValue());  return (<View><Text>{myClass.getValue()}</Text></View>  );}

If it's helpful, this is my class definition:

export default class MyClass {  private title: string = "";  private value: number = 1;  // Getters/Setters...}

When this renders, I get the following in my logs:

❌    typeof:                object❌    object value:          [object Object]✅    object variable title: New Title✅    object variable value: 1

But I would expect something like this:

✅    typeof:                MyClass✅    object value:          {"title":"New Title","value":1}✅    object variable title: New Title✅    object variable value: 1

Is there a way to have useState respect the class of my state object?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>