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

After combining multiple types, how to access the properties as optional properties? #40128

Closed
JYC-99 opened this issue Aug 19, 2020 · 1 comment

Comments

@JYC-99
Copy link

JYC-99 commented Aug 19, 2020

TypeScript Version: 3.9.2

Search Terms:

Expected behavior:

obj.doSomethingA?.();

obj.doSomethingA ? obj.doSomethingA() : null;

Should work.

Actual behavior:

End up with error:

Property 'doSomethingA' does not exist on type 'TMyInterface'.
  Property 'doSomethingA' does not exist on type 'IInterfaceB'.

I have to use type casting to work around.

Related Issues:

Code

interface IInterfaceA {
    doSomethingA(): void;
}

interface IInterfaceB {
    doSomethingB(): void;
}

type TMyInterface = IInterfaceA | IInterfaceB;

const gen = (): TMyInterface => {
    if (Math.random() > 0.5) {
        return {
            doSomethingA: () => {}
        };
    }

    return {
        doSomethingB: () => {}
    }
}

const obj = gen();

obj.doSomethingA?.();

obj.doSomethingA ? obj.doSomethingA() : null;
Output
"use strict";
var _a;
const gen = () => {
    if (Math.random() > 0.5) {
        return {
            doSomethingA: () => { }
        };
    }
    return {
        doSomethingB: () => { }
    };
};
const obj = gen();
(_a = obj.doSomethingA) === null || _a === void 0 ? void 0 : _a.call(obj);
obj.doSomethingA ? obj.doSomethingA() : null;
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

@jcalz
Copy link
Contributor

jcalz commented Aug 19, 2020

This is not a forum for asking TS questions; it's for reporting bugs or requesting features. And when you report a bug or request a feature, you are expected to search existing GitHub issues to see if it has been raised before.

This is a duplicate of #33736 and #1260

@JYC-99 JYC-99 closed this as completed Aug 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants