Using AWS DataStore.query returns an object whose properties are parsed objects, but linter expects a string

290 Views Asked by At

When I use DataStore.query to retrieve data, I am getting conflicting data types from my linter. Contrived example:

schema.graphql

type Card @model @auth(rules: [{ allow: private }]) {
  id: ID!
  input: AWSJSON  
}

react component javascript:

 const originalCard = await DataStore.query(Card, cardid);
 // originalCard.input is of type string | undefined | null according to my linter
 if(!originalCard.input) return; // Ignore non-string cases
 await DataStore.save(
   Card.copyOf(originalCard, (updated) => {
     updated.input = JSON.stringify(originalCard.input);
   })
 );

The above should simply save the same input as it has already received. And this is accepted by my linter. The problem is that when I run the code, I get an error, which advises that the originalCard.input value is actually an object. So it seems that DataStore.query is parsing the input value for me, which is great, except that the linter is being given the wrong information.

The cheap and dirty fix is just to tell typescript that the input value is in fact an object: ...as unknown as Record<string,any>, but I suspect there's a better way and/or I'm doing something wrong?

1

There are 1 best solutions below

1
Robert Rendell On

Why don't you try adding a type narrowing check, so that TypeScript can statically analyse the logic path:

const originalCard = await DataStore.query(Card, cardid);
if(typeof originalCard.input === 'object') {
  await DataStore.save(
   Card.copyOf(originalCard, (updated) => {
     updated.input = JSON.stringify(originalCard.input);
   })
 );
}

So this would replace if(!originalCard.input) return;