打字稿根据类属性缩小类型(来自 .filter、.find 等) [英] Typescript narrow down type based on class property (from .filter, .find, etc.)
本文介绍了打字稿根据类属性缩小类型(来自 .filter、.find 等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在调用数组 .filter
或 .find
I want to narrow down type based on the class property when calling array .filter
or .find
class Square {
type: "square";
constructor() {
this.type = "square";
}
}
class Circle {
type: "circle";
constructor() {
this.type = "circle";
}
}
const objects = [
new Circle(),
new Square(),
new Circle(),
new Square(),
];
// I want `circles` to be Circle[], not (Circle | Square)[]
const circles = objects.filter(o => o.type === "circle");
// I want `square` to be Square | undefined, not Circle | Square | undefined
const square = objects.find(o => o.type === "square");
这在 Typescript 中可行吗?
Is this possible in Typescript?
推荐答案
您可以使用 类型保护功能.下面是一个提前定义了类型保护函数的例子:
You can do this with type guard functions. Here's an example with the type guard functions defined ahead of time:
function isSquare(obj: {type: string}): obj is Square {
return obj.type === "square";
}
function isCircle(obj: {type: string}): obj is Circle {
return obj.type === "circle";
}
// ...
// I want circles to be Circle[]
const circles = objects.filter(isCircle);
// I want square to be Square | undefined
const square = objects.find(isSquare);
...但它们也可以是内联的:
...but they can also be inline:
// I want circles to be Circle[]
const circles = objects.filter((obj): obj is Circle => obj.type === "circle");
// I want square to be Square | undefined
const square = objects.find((obj): obj is Square => obj.type === "square");
这篇关于打字稿根据类属性缩小类型(来自 .filter、.find 等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文