Open WarpedPixel opened 1 week ago
I think this is a duplicate of https://github.com/openapi-ts/openapi-typescript/issues/1727?
Seems related for sure. But I don't understand how this is desired behavior. I also wonder how it relates to issue #1018 where it seems things were moving in the direction of removing | undefined
not adding it.
I am no Typescript expert, but the intention here is to declare a dictionary, that maps str to str. Not to anything else. It is type checked at the source (Python backend in this case) to ensure that is true.
class SupportedLanguages(BaseModel):
languages: dict[str, str]
That then becomes an openAPI spec:
"SupportedLanguages": {
"properties": {
"languages": {
"additionalProperties": {
"type": "string"
},
"type": "object",
"title": "Languages"
}
},
"type": "object",
"required": [
"languages"
],
"title": "SupportedLanguages"
}
Which is the way to describe a dictionary in OpenAPI AFAIK.
No dictionary has all the keys, obviously. But in my case, if it has a key it maps to a string.
In fact, in my Typescript code I declare the array that holds the languages as
languages: {
[key: string]: string;
};
The intention was to declare a dictionary that maps certain strings to strings (not to null or undefined). This is now incompatible with the type opeanapi-typescript 7.0.0 creates. This declaration makes languages['some str not in dict']
return undefined, but it prevents me from storing undefined in the dictionary (good). It seems that adding | undefined
would not be helpful here in my case.
What is the suggested fix or best practice in this case? Declare all Typescript dictionaries with | undefined
? Is there some option to change behavior of openapi-typescript?
Strong agree with @WarpedPixel. I had to stay on version 6 because of this.
I think the intent vs. the implementation might be confused. I understand that it's an effort to prevent you from assuming a key exists. But simply checking for the existence of the key does not remove the undefined
from the union.
Contrast that with what the schema is actually declaring, which is that if a key exists, then here are the only allowed values. undefined
makes no sense to include there, because it is not an allowed value for a given key that exists.
Description
A dictionary of string -> string defined in the openapi.json spec, generates a string -> string | undefined dictionary in Typescript. This worked as expected with 6.7.7.
openapi-typescript
7.0.0
v20.14.0
macOS 14.5
Reproduction
Excerpts from
openapi.json
Expected result
Output from 6.7.7:
Actual result
Output from 7.0.0:
Checklist
npx @redocly/cli@latest lint
)