0

Problem:

Is there a way to tell codegen or typescript to remove ? optional chaining.

post.attributes?.Title to post.attributes.Title

since Title is defined in the getPosts query.


Here's the code example.

export type Post = {
  __typename?: 'Post';
  Body?: Maybe<Scalars['String']>;
  Slug?: Maybe<Scalars['String']>;
  Title?: Maybe<Scalars['String']>;
  createdAt?: Maybe<Scalars['DateTime']>;
  publishedAt?: Maybe<Scalars['DateTime']>;
  updatedAt?: Maybe<Scalars['DateTime']>;
};

export type PostEntity = {
  __typename?: 'PostEntity';
  attributes?: Maybe<Post>;
  id?: Maybe<Scalars['ID']>;
};
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import _ from 'lodash';

import type { GetPostsQuery, PostEntity } from '../../common/cms/types';

const client = new ApolloClient({
  uri: 'http://127.0.0.1:1337/graphql',
  cache: new InMemoryCache(),
});

// read up on different code gen types
async function getPosts() {
  return await client.query<GetPostsQuery>({
    query: gql`
      query getPosts {
        posts {
          data {
            id
            attributes {
              Title
              Body
            }
          }
        }
      }
    `
  });
}

export default async function NotesPage() {
  const queryResult = await getPosts();

  const posts = queryResult.data.posts?.data

  console.log('posts', posts);

  return (
    <div className='bg-slate-500 h-screen w-screen flex-col justify-center items-center'>
      <div className='space-y-3'>
        {_.map(posts, (post: PostEntity) => (
          <div className='p-2 bg-slate-400' key={post.id}>
            <div>{post.attributes?.Title}</div>
            <div>{post.attributes?.Body}</div>
          </div>
        ))}
      </div>
    </div>
  );
}
starball
  • 20,030
  • 7
  • 43
  • 238
v0rs4
  • 106
  • 5
  • Why not remove the optional chaining from the source? Why try get the transpiler/compiler to do it? Why try to remove it at all? – starball Jan 06 '23 at 20:32

0 Answers0