In typescript I refer to type:
structuredOutput?: BaseModelParams['generationConfig']['responseSchema']
The problem is that inside BaseModel the generationConfig is optional:
and you want to refer to GenerationConfig['responseSchema'] via BaseModelParams['generationConfig']['responseSchema'], but generationConfig is optional, so TypeScript complains.
Solution
You need to safely access the nested type, accounting for the possibility that generationConfig could be undefined.
You can do this with a conditional type:
ts
type StructuredOutput = BaseModelParams['generationConfig'] extends undefined
? undefined
: BaseModelParams['generationConfig'] extends { responseSchema: infer R }
? R
: undefined;
Or, more simply, if you want the type to be GenerationConfig['responseSchema'] | undefined:
ts
type StructuredOutput = BaseModelParams['generationConfig'] extends { responseSchema: infer R }
? R
: undefined;
Or, if you want to directly reference the type and allow for undefined:
ts
type StructuredOutput = GenerationConfig['responseSchema'] | undefined;
Why not use BaseModelParams['generationConfig']['responseSchema']?
Because generationConfig is optional, TypeScript will not allow you to directly index into it.
If you want to keep the reference through BaseModelParams, you can use the following utility type:
ts
type StructuredOutput = NonNullable<BaseModelParams['generationConfig']>['responseSchema'];
This works because NonNullable<T> removes null and undefined from T.
Final Recommendation
Best practice:
Reference the type directly from GenerationConfig:
Summary:
You cannot safely use BaseModelParams['generationConfig']['responseSchema'] directly because generationConfig is optional.
Use GenerationConfig['responseSchema'] or NonNullable<BaseModelParams['generationConfig']>['responseSchema'] instead.