Answer the question
In order to leave comments, you need to log in
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 // При этом работает все корректно. Обратиться к переменным в таком случае нельзя
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question