Home > Enterprise >  How to declare usestate when using dependency to custom object something like { filter[], sort[] }
How to declare usestate when using dependency to custom object something like { filter[], sort[] }

Time:11-11

I want to declare useState Hook with an custom object which has two arrays something like below

const [initConfig, setInitConfig] = useState<>({filter:[], sort:[]});

But I do not know how to declare inside the angle bracket.

filter array will have items of type

export interface IFilterTerm {
    key: string;
    criteria?: CriteriaType;
    value: string;
}

sort will have items of type

type ISortGridItem = {
    colId: string | undefined;
    sort: string | null | undefined;
}

I am setting values using below

setInitConfig({
      filter : [...persistentConfig.filter],
      sort : [...persistentConfig.sort]
    });
const persistentConfig = {
    filter: [ 
      { key:TIME, criteria: CriteriaType.DataRange, "value":"currentBusinessDay"},
      { key:INCLUDE_SYNTHETIC_LEGS, criteria: CriteriaType.Equals, value:"false" },
      { key:"waterfall", criteria: CriteriaType.Equals, value:"true" } 
    ],
    sort: [
      {
        colId: "time",
        sort: "asc"
      }
    ]
  }  

I tried to declare usestate like

const [initConfig, setInitConfig] = useState<{ filter: IFilterTerm[] , sort: ISortingTerm }[]>({filter:[], sort:[]});

but no luck. I am getting error

Argument of type '{ filter: never[]; sort: never[]; }' is not assignable to parameter of type '{ filter: IFilterTerm[]; sort: ISortingTerm; }[] | (() => { filter: IFilterTerm[]; sort: ISortingTerm; }[])'.
Types of property 'filter' are incompatible.
Type 'never[]' is not assignable to type '{ <S extends { filter: IFilterTerm[]; sort: ISortingTerm; }>(predicate: (value: { filter: IFilterTerm[]; sort: ISortingTerm; }, index: number, array: { filter: IFilterTerm[]; sort: ISortingTerm; }[]) => value is S, thisArg?: any): S[]; (predicate: (value: { ...; }, index: number, array: { ...; }[]) => unknown, thisA...'.
Type 'never[]' provides no match for the signature '<S extends { filter: IFilterTerm[]; sort: ISortingTerm; }>(predicate: (value: { filter: IFilterTerm[]; sort: ISortingTerm; }, index: number, array: { filter: IFilterTerm[]; sort: ISortingTerm; }[]) => value is S, thisArg?: any): S[]'.

CodePudding user response:

You have a typo in your TypeScript:

const [initConfig, setInitConfig] = useState<{ filter: IFilterTerm[] , sort: ISortingTerm }[]>({filter:[], sort:[]});

Where you have useState<{ filter: IFilterTerm[] , sort: ISortingTerm }[]>, you have the array brackets in the wrong spot. They need to be next to ISortingTerm, not on the outside of the curly braces. It should look like this:

const [initConfig, setInitConfig] = useState<{ filter: IFilterTerm[] , sort: ISortingTerm[] }>({filter:[], sort:[]});
  • Related