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");
Is this possible in Typescript?