Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Closed
anas-araid opened this issue Sep 19, 2022 · 4 comments
Closed

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

anas-araid opened this issue Sep 19, 2022 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@anas-araid
Copy link

anas-araid commented Sep 19, 2022

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)

@fatcerberus
Copy link

fatcerberus commented Sep 19, 2022

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
Copy link

fatcerberus commented Sep 19, 2022

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
Copy link
Contributor

Also related: #20863

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Sep 19, 2022
@typescript-bot
Copy link
Collaborator

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

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

5 participants