dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
5.03k stars 196 forks source link

`MethodSignature.getReturnType()` does not support `T | undefined` (optional/nullable return types) #1563

Closed mrousavy closed 3 months ago

mrousavy commented 3 months ago

Description

I have the following TS type:

interface Something {
  someFunc(): number | undefined
}

When getting the method someFunc as a MethodSignature, I can get it's return type using getReturnType():

const method = declaration.getMethods()[0]
const returnType = method.getReturnType()
console.log(returnType.getText())

..but instead of being number | undefined, this actually is just number!

Version: 23.0.0

Expected behavior

I expect the returnType to either be number and isNullable() to be true (ideal case), or an union of number | undefined.

But instead, it is just number. No optional/undefined.

mrousavy commented 3 months ago

Same goes for method.getSignature().getReturnType().getText()

getDriver(car: Car): Person | undefined

👇

"Person"
mrousavy commented 3 months ago

Ah, sorry I didn't have strictNullChecks enabled in my Project:

const project = new Project({
  compilerOptions: {
    strict: true,
    strictNullChecks: true,
  },
})

(or just load the tsconfig.json)