Skip to content

TypeScript doesn't warn me that a property is missing #50845

Closed
@anas-araid

Description

@anas-araid

Bug Report

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type DataType = {
  value: (Data & Extra) | Data;
};

type Data = {
  type1: string;
};

type Extra = {
  isEditable: boolean;
  onChange: () => void;
};

const data: DataType = {
  // value should throw an error (onChange is not specified)
  value: {
    type1: 'type',
    isEditable: true,
  },
};

πŸ™ Actual behavior

TypeScript ignores this definition ((Data & Extra) | Data)

πŸ™‚ Expected behavior

I expect TypeScript to warn me that a property within value is missing: e.g (onChange is not specified)

Activity

fatcerberus

fatcerberus commented on Sep 19, 2022

@fatcerberus

The value you've provided is not a valid Data & Extra, but it is a valid Data (the types aren't exact, objects can have extra properties). Since the type of .value is (Data & Extra) | Data, there is no type error in this code.

fatcerberus

fatcerberus commented on Sep 19, 2022

@fatcerberus

Just to reiterate/clarify: Because objects can have more properties than their type calls for, unions of object types are not mutually exclusive. If you want a mutually exclusive type you need to use a discriminated union.

MartinJohns

MartinJohns commented on Sep 19, 2022

@MartinJohns
Contributor

Also related: #20863

typescript-bot

typescript-bot commented on Sep 21, 2022

@typescript-bot
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

        Participants

        @fatcerberus@MartinJohns@RyanCavanaugh@typescript-bot@anas-araid

        Issue actions

          TypeScript doesn't warn me that a property is missing Β· Issue #50845 Β· microsoft/TypeScript