Skip to content

Tagged unions not inferred when returning objects implementing interfaces #11146

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

Closed
mmc41 opened this issue Sep 26, 2016 · 1 comment
Closed
Labels
Question An issue which isn't directly actionable in code

Comments

@mmc41
Copy link

mmc41 commented Sep 26, 2016

TypeScript Version: 2.0.0

interface Category 
{
    id: string;
    description: string;
}

interface TreeNodeBase 
{
  readonly children: TreeNode[];
  title() : string;
  id(): string;
}

interface CategoryTreeNode extends TreeNodeBase
{
  readonly kind: "category";
  readonly item: Category;
}

interface EmptyTreeNode extends TreeNodeBase
{
  readonly kind: "empty";
}

type TreeNode = EmptyTreeNode | CategoryTreeNode; // More variants in actual case.

function createCategoryNode(category : Category, children : TreeNode[]) : CategoryTreeNode
{
    return {
      kind: "category",
      item: category,
      children: children,
      title() { return (<Category>this.item).description; }, // Why is type of this.item not inferred ?
      id() { return (<Category>this.item).id; } // Why is type of this.item not inferred ?
    };
}

Expected behavior:

The factory method createCategoryNode should be able to return an object that is a CategoryTreeNode in a type safe manner without having to specify the type as done above when implementing the title and id functions.

Actual behavior:

Right now, unless the type of this.item is explicitly given, typescript will regard the type of item as any instead of Category. Thus, the type of this.item is not inferred correctly.

@Arnavion
Copy link
Contributor

Arnavion commented Sep 26, 2016

Nothing to do with union types. this itself is any in methods in object literals. See #10835

Edit: i.e. in your case you would need to write

    title(this: CategoryTreeNode) { return this.item.description; }
    id(this: CategoryTreeNode) { return this.item.id; }

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Sep 26, 2016
@mhegazy mhegazy closed this as completed Sep 26, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants