简体   繁体   中英

type of custom object in typescript

I'm new to typescript and I created this object:

const initialState = {
    title: {
        value: "",
        error: false
    },
    amount: {
        value: 0,
        error: false
    },
    type: "Food",
    time: new Date()
} 

I want to use is as initial state of a useState. therefore I want to now what I need to passe as type to my useState. const [Form, setForm] = useState< "what should come here?" >(initialState) const [Form, setForm] = useState< "what should come here?" >(initialState) ;

thanks in advance,

interface IState {
  title: {
    value: string;
    error: boolean;
  };
  amount: {
    value: number;
    error: boolean;
  };
  type: string;
  time: Date;
}

const [Form, setForm] = useState<IState>(initialState);

You could do something like this:

interface SomeName {
    value: string;
    error: boolean;
}

interface IState {
  title: SomeName;
  amount: SomeName;
  type: string;
  time: Date;
}

const initialState: IState = {
    title: {
       value: "",
       error: false
    },
    amount: {
       value: 0,
       error: false
    },
    type: "Food",
    time: new Date()
} 

const [Form, setForm] = useState<IState>(initialState);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM