This repository has been archived by the owner on Mar 26, 2024. It is now read-only.
Get type of item in optional array #196
-
Hi, love this project 😄 I've used the code gen to generate types, and one of my generated document types looks like this:
Now in my app I want to create a component that renders one single event, and I want to extract the type like this:
But since the MyDocument['events']-array is optional it doesn't work. Do you have any suggestions as to how I can dig out this type? The error I get looks something like this:
|
Beta Was this translation helpful? Give feedback.
Answered by
ricokahler
Sep 20, 2021
Replies: 1 comment 1 reply
-
hi there!, thanks for the kind words. I have two potential solutions for you:
export default {
name: 'myDocument',
type: 'document',
fields: [
{
name: 'aRequiredField',
type: 'string',
// 👇👇👇
codegen: { required: true },
validation: (Rule) => Rule.required(),
// 👆👆👆
},
],
};
type MyDocument = { events?: Array<{_type: 'something'}> }
type SafeIndexedAccess<
T extends { [key: string]: any } | undefined,
K extends keyof NonNullable<T>,
> = T extends undefined ? NonNullable<T>[K] | undefined : NonNullable<T>[K];
type Props = SafeIndexedAccess<MyDocument['events'], number>
// results in: type Props = { _type: 'something'; } | undefined or without the helper 🤷: type Props = NonNullable<MyDocument['events']> | undefined; |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
winsvold
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi there!, thanks for the kind words.
I have two potential solutions for you:
codegen: { required: true }
. This will make the codegen assert your field as required (this will not be enforced so be careful to add the corresponding validation too.