It's frustrating that in the example below, I encounter a typescript error despite the fact that the error is not logically possible to occur in the code. The function receives either Category1 or Category2 and when it returns the ComputedCategory
, both the computed
and name
properties will have the same value. However, TypeScript fails to recognize this and suggests that the values could be from either union type. This leads to an error when trying to set the name property, claiming that
{ computed: 'category1', name: 'category2' }
cannot be assigned to ComputedCategories
. Why does TypeScript behave like this and why can't it understand that these values are impossible? Secondly, how should I define the type without resorting to numerous type guards with specific returns, which defeats the purpose of my approach? Is this a bug or am I misunderstanding something?
type Category1 = {
testName: 'category1';
name: 'category1'
};
type Category2 = {
testName: 'category2';
name: 'category2'
};
type Categories = Category1 | Category2;
type ComputedCategory1 = {
computed: 'category1'
name: 'category1'
};
type ComputedCategory2 = {
computed: 'category2'
name: 'category2'
};
type ComputedCategories = ComputedCategory1 | ComputedCategory2;
const computeCategory = (category: Categories): ComputedCategories => ({
computed: category.testName,
name: category.name
})
// ERROR
Type '{ computed: "category1" | "category2"; name: "category1" | "category2"; }' is not assignable to type 'ComputedCategories'.
Type '{ computed: "category1" | "category2"; name: "category1" | "category2"; }' is not assignable to type 'ComputedCategory2'.
Types of property 'computed' are incompatible.
Type '"category1" | "category2"' is not assignable to type '"category2"'.
Type '"category1"' is not assignable to type '"category2"'.ts(2322)