Home > front end >  Setting dictionary of objects as type for useState() in TS/React function components
Setting dictionary of objects as type for useState() in TS/React function components

Time:01-13

I am trying to switch from classes to function components.

If I have a datasets interface already defined and would like a state variable
// datasets: {[fieldName: string]: Dataset};
// Example: {"a": datasetA, "b": datasetB}

Is this a valid way to write it?
const [datasets, setDatasets] = useState <{[fieldName: string]: Dataset}> ({});

CodePudding user response:

Yes, this should typecheck as is!

You can also define a type to hold the Dataset records, and pass that to useState:

import "./styles.css";
import {useState} from 'react';

type Dataset = {};
type DatasetRecord = {
  [fieldName: string]: Dataset;
}

export default function App() {
const [datasets, setDatasets] = useState<DatasetRecord>({});
  return (...);
}

See demo here.

CodePudding user response:

This is a valid type for useState

const [datasets, setDatasets] = useState<{[fieldName: string]: Dataset}> ({});

However, you can shorten it a bit using Record:

const [datasets, setDatasets] = useState<Record<string, Dataset>> ({});
  •  Tags:  
  • Related