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

Error when accessing to optional argument of overloaded function inside correct type guard #38022

Closed
jareguo opened this issue Apr 17, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@jareguo
Copy link

jareguo commented Apr 17, 2020

TypeScript Version: 3.8.3

Search Terms: type guard function optional overload

Code

class MyClass {
    foo () {}
}

function add (test: number): void;
function add (test: object, paramIfObject: MyClass): void;  // should overload this declaration
function add (test: number | object, paramIfObject?: MyClass): void {
    if (typeof test === 'object') {  // Indicated the argument to overload is not optional
        paramIfObject.foo();   // Error: Object is possibly 'undefined'.(2532)
    }
}

Expected behavior: Compile successfully

Actual behavior: Error: Object is possibly 'undefined'.(2532)

Description: The variable paramIfObject was used inside the if statement, which should be a type guard refering to the correct function overload. So the variable should not compiled as an optional argument. Just equals to this: (no error)

image

Playground Link: Playground Link

Related Issues:

Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "useDefineForClassFields": false,
    "alwaysStrict": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "downlevelIteration": false,
    "noEmitHelpers": false,
    "noLib": false,
    "noStrictGenericChecks": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "esModuleInterop": true,
    "preserveConstEnums": false,
    "removeComments": false,
    "skipLibCheck": false,
    "checkJs": false,
    "allowJs": false,
    "declaration": true,
    "experimentalDecorators": false,
    "emitDecoratorMetadata": false,
    "target": "ES2017",
    "module": "ESNext"
  }
}
@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 17, 2020
@RyanCavanaugh
Copy link
Member

See #14515

@jareguo
Copy link
Author

jareguo commented Apr 18, 2020

Thanks

@jareguo jareguo closed this as completed Apr 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants