#How to set a useState with an empty object, and then type it?

13 messages · Page 1 of 1 (latest)

naive chasm
#

So, I have something like this:

const [value, setValue] = useState<SomeType>({} as SomeType);

The problem is I have to use "as SomeType" when I initialize AND when I reset that "value" to an empty object.

How would I just create a single type that would mean "SomeType" or empty object.. I did the following, but it didn't work

type SomeType =
  | ProductSkus & {color: string}
  | Record<string, never>;

I also tried:

type SomeType =
  | ProductSkus & {color: string}
  | object;

neither worked.

balmy scroll
#

your empty object is mutable

#

so it might not stay an empty object

coarse gust
#

Usually you might initialise it with a value of undefined and you can use it as such: useState<SomeType>() and then check for undefined when you use it

balmy scroll
#

whats your error?

type ProductSkus = Record<string, unknown>;
type SomeType = (ProductSkus & { color: string }) | Record<string, never>;

export default function App() {
  const [value, setValue] = useState<SomeType>({});

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

this works for me

naive chasm
#

my apologies, here is what is causing the error:

setValue({...value, ...item2});

"value" here is the previous state, merged with a partial object. I did it this way because using a function within the setValue had some rendering issues.

#

The error is along these lines:

 Property 'id' is incompatible with index signature.         Type 'string | number' is not assignable to type 'never'.           Type 'string' is not assignable to type 'never'.


#

I also wasn't clear, the type "ProductSkus" is a full fledged object with a bunch of key/values, so the type of that can't/shouldn't be Record<string, unknown>, I was only using that to define/type the {}

balmy scroll
#

the product skus type shouldnt matter

#

so

#

what is the type of item2? if it's a SomeType, it should work. if it's only a Partial<SomeType> or it's some other type, it won't work because you may be spreading some value into the object that SomeType shouldn't have, or it may be missing a value that it needs

naive chasm
#

item2 is ProductSku

#

let me double check to see if I am "adding" anything in tere,