mph85
mph85

Reputation: 1356

Converting JS to TS - React Hooks

I'm making a basic chat app with React w/Typescript. I understand that TS requires type declaration.

I would like to convert this from JS to TS, what all would need to be changed and where do I declare the type in each case?

CODE

function App() {

 const [rooms, setRooms]   = useState(''); // type str
 const [roomId, setRoomId] = useState(''); // type str
 const [user, setUser]     = useState(''); // type str

function updateRoom(id) {

 return id === '' ? setRoomId('') : setRoomId(id) // ??

}

return (
 <div className="app">
   <div className="room">
   {rooms.map((room, index) => (
     <Room key={index} index={index} room={room} />
   ))}
 </div>
</div>
)
}

TS

function App() {

   const [rooms, setRooms] type Str = useState(''); 

}

Would it be something like this?

Upvotes: 0

Views: 330

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 186984

Typescript only requires typing where it can't be inferred.

const [rooms, setRooms] = useState('');

Because of how useState is typed, typescript knows that when passed a string, it will return something like this type:

[string, (newRooms: string) => void]

Which gets destructured into your value and your setter.

So typescript will know that rooms will be a string because you pass a string to useState.

This code should work as is in typescript. Just convert it and fix what errors come up.


But in case it can't be inferred, you can give it a hint:

const [foo, setFoo] = useState(null as string | null)

Now foo could be null or string, but null is the default value on component mount.

Upvotes: 1

Related Questions