【发布时间】:2020-03-21 19:42:50
【问题描述】:
我经常使用下面示例中的代码,想知道是否有一些聪明的方法可以键入 find 结果而无需进行显式类型断言。
type Foo = { type: "Foo" };
type Goo = { type: "Goo" };
type Union = Foo | Goo;
const arr: Union[] = [];
const foo = arr.find(a => a.type === "Foo") as Foo;
如果省略as Foo 类型断言,则结果为Union 类型,即使它只能返回Foo 类型。
在此类示例中,修复 find 类型以返回缩小类型的最简洁方法是什么?
编辑:这个问题也可能适用于filter 和其他类似的方法。
Edit2:建议的类似问题的接受答案 (Way to tell TypeScript compiler Array.prototype.filter removes certain types from an array?) 表明,通过在 find/filter 的谓词中使用类型保护,可以缩小返回值。
这种类型保护函数应该如何缩小任何有区别的联合,例如区分字符串文字总是在type 键下?
【问题讨论】:
-
不完全,但它有帮助。现在只是想弄清楚如何编写一些通用类型保护函数来缩小像这样的可区分联合,这样我就可以编写
arr.find(isTypeFromUnion("Foo"))。 -
您可以将
find的回调函数定义为类型保护,如下所示:const maybeFoo = arr.find((a): a is Foo => a.type === "Foo"); // Foo | undefined。 TS -
这只是将
as Foo移动到a is Foo,这意味着我仍然需要显式编写类型 -
Afaik 目前无法让编译器自动推断类型保护并缩小联合,请参阅 here 和 this issue。
标签: typescript type-conversion discriminated-union