Skip to content

Returning union of interfaces and conditional parameters #18230

Closed
@armano2

Description

@armano2

TypeScript Version: 2.5.2

Code

enum Types {
  TYPE_A = 'TYPE_A',
  TYPE_B = 'TYPE_B',
}

interface ITypeA {
  type : Types.TYPE_A
  variable : string
}

interface ITypeB {
  type : Types.TYPE_B
  variable : string
}

function myFunction (variable : string) : ITypeB | ITypeA {
  const type = (variable === 'A') ? Types.TYPE_A : Types.TYPE_B
  return {
    type,
    variable,
  }
}

Expected behavior:
there should be no type error
Actual behavior:

Type '{ type: Types; variable: string; }' is not assignable to type 'ITypeA | ITypeB'.
  Type '{ type: Types; variable: string; }' is not assignable to type 'ITypeB'.
    Types of property 'type' are incompatible.
      Type 'Types' is not assignable to type 'Types.TYPE_B'.

This code should work same as, because there is no logical distinction between them

function myFunction (variable : string): ITypeB | ITypeA {
  if (variable === 'A') {
    return {
      type: Types.TYPE_A,
      variable,
    }
  } else {
    return {
      type: Types.TYPE_B,
      variable,
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions