I
I
ivan05122020-03-23 20:06:52
typescript
ivan0512, 2020-03-23 20:06:52

Why is there no error when using the intersection type?

There was such a question, when using the union type, the assigned object must be either type1 or type2. This object obviously cannot be assigned to type1, since property b is missing, however, if we assume that it is type2, then there is also an extra property, that is, there should also be an error when assigning an object literal. However, TS does not consider this a mistake. Why is that?

type type1 = {
  a: number;
  b: number;
};

type type2 = {
  c: number;
};

type type3 = type1 | type2;

const test1: type3 = { // Тут должна быть ошибка
  a: 111,
  c: 222,
};

test1.a // При этом работает все корректно. Обратиться к переменным в таком случае нельзя


Is this a ts bug or am I missing something?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2020-03-24
@lorus

And this is not a mistake at all. In a variable of type type1 | type2 can be assigned a value of type type1 or type2. Your value is of type type2, so you're good to go. As for the "extra" property "a", its presence, strictly formally, is not a mistake. Theoretically, there can be any additional field. But TypeScript does not allow this, to prevent _human_ errors. This is something like linting, although strictly formally, as I said, this is not a mistake.
Here is the relevant comment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question