Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG][typescript-fetch] error TS2532: Object is possibly 'undefined' for optional model properties #17970

Closed
5 of 6 tasks
kota65535 opened this issue Feb 27, 2024 · 2 comments · Fixed by #17972
Closed
5 of 6 tasks

Comments

@kota65535
Copy link
Contributor

kota65535 commented Feb 27, 2024

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

Given OpenAPI schema definition:

title: Task
description: Task
type: object
properties:
  id:
    type: integer
    readOnly: true
  title:
    type: string
  dueDate:
    type: string
    format: date
required:
  - id
  - title

Then generated source file Task.ts has a compilation error TS2532: Object is possibly undefined. The TypeScript version is 5.3.3 (latest).

image

openapi-generator version

At the current latest commit of the master branch (a8efb8e)

OpenAPI declaration file content or url
Generation Details
Steps to reproduce
Related issues/PRs

This bug seems to have been introduced by #17798.

Suggest a fix

Typescript compiler does not understand the function exists() ensures the value is present. exists() simply assert the value is not null or undefined, so a quick fix will be using == operator like this.

        'dueDate': value['dueDate'] == null  ? undefined : ((value['dueDate']).toISOString().substring(0,10)),
@wing328
Copy link
Member

wing328 commented Mar 9, 2024

FYI @noordawod - the author of #17798

@topce
Copy link
Contributor

topce commented Mar 10, 2024

Nice work @kota65535
Small remark
expression in

'dueDate': value['dueDate'] == null  ? undefined : ((value['dueDate']).toISOString().substring(0,10)), 

could be written in typescript

'dueDate': value.dueDate?.toISOString().substring(0,10)),

or

'dueDate': value['dueDate']?.toISOString().substring(0,10)),

so called optional chaining
could be future improvement
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants