Skip to content

Strange behavior with union of complex types #23162

Closed
@Roaders

Description

@Roaders

TypeScript Version: 2.8.1

Search Terms:
union complex types

Code

interface IOne{
    stringOne: string;
    numberOne: number;
}

interface ITwo{
    stringTwo: string;
    numberTwo: number;
}

type IEitherOr = IOne | ITwo;

var itemThree: IEitherOr = {
    numberOne: 42343,
    stringOne: "",

    numberTwo: "sdfsd"
}

Expected behavior:
This should throw an error.
IMHO I think that there are 3 issues here.

  • First off I was surprised that numberTwo was allowed AT ALL. I think that the type should be either IOne OR ITwo, not a mix of the two.
  • If we do allowed mixed types (which I don't think we should) then surely if there are any properties for ITwo we should require all of them. This should throw an error unless we have specified both numberTwo and stringTwo
  • lastly it's not even type checking numberTwo. It is typed as a number but it's fine with a string.

Actual behavior:
The compiler is fine with this!

Playground Link:
Link

Work Around:

You can enforce proper type checking on the secondary mixed type like this:

type IFixedEitherOr =
    ( IOne & Partial<ITwo> ) 
    |
    ( ITwo & Partial<IOne> );

var itemFour: IFixedEitherOr = {
    numberOne: 42343,
    stringOne: "",

    numberTwo: "dfgdf" // this errors
}

The code above correctly fails to compile.

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