【发布时间】:2023-03-30 06:49:01
【问题描述】:
在下面的示例中,我收到了一个打字稿错误,即使该错误实际上永远不会在代码中发生。我要么将 Category1 或 Category2 传递给函数,因此当返回 ComputedCategory 类型时,它在 computed 和 name 属性下将具有相同的值,但是打字稿无法识别这一点。它认为该值可以来自任一工会。例如,在设置 name 属性时,它会抛出一个错误,基本上是说 { computed: 'category1', name: 'category2' } is not assignable to ComputedCategories' 首先为什么打字稿这样做,为什么它不够聪明,无法意识到这些值是不可能的,第二怎么办我正确地写这个来表达类型?我希望该示例不使用一堆具有特定返回的类型保护,因为这正是我想要避免的。这是一个错误还是我做错了什么?
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)
【问题讨论】:
标签: typescript types typescript-generics