0

I have the following sanity-schema.ts:

export type Character = {
  _type: "character";
  /**
   * Character Name — `string`
   *
   *
   */
  words: "spokenWords";
  /**
   * Spoken Words — `string`
   *
   *
   */
};

export type Book = {
  _type: "book";
  /**
   * Author — `string`
   *
   *
   */
  title: "title";
  /**
   * Title — `string`
   *
   *
   */
};

export type Documents =
  | Character
  | Book

I am calling data from sanity like so and asserting its type:

const data: unknown[] = await client.fetch(DocumentQuery);
const documentsData: Documents[] = data as Documents[];

Filtering through the documentsData to unpack it separately and assert both types I have the following:

 const characterData: Character = documentsData.filter(
    (d: Documents) => d._type === "character"
  )[0] as Character;

However the following error renders on the webpage:

Cannot read properties of undefined (reading 'title')

And when I console.log(characterData) it is undefined.

What am I doing wrong?

rowen
  • 49
  • 6

0 Answers0