扩展类型以创建子类型



我正在使用TypeScript,我想知道如何实现另一个child类型。我不知道该如何描述我所追求的东西,所以让我举个例子。

type Person = {
name: string;
type: PersonType
}
type Child = Person & {
type: PersonType.child,
}
enum PersonType {
adult = "adult",
child = "child",
}
const people: Person[] = [...];
const children: Child[] = people.filter(p => p.type === PersonType.child);

这是我将使用通用的东西吗?我会认为这是直截了当的,我只是少了一部分。谢谢!

枚举中添加了多余的=符号。

type Person = {
name: string;
type: PersonType
}
type Child = Person & {
type: PersonType.child,
}
enum PersonType {
adult = "adult",
child = "child",
}
type TestChild = Person extends Child ? true : false // false
type TestPerson = Child extends Person ? true : false // true

const people: Person[] = [{ name: 'John', type: PersonType.adult }, { name: 'Tim', type: PersonType.child }];
const children: Child[] = people.filter(p => p.type === PersonType.child);

问题是Child扩展了Person,而不是相反。您不能仅为children常量显式地使用Child[]类型,因为Person不扩展Child

这是一篇关于协方差的有趣文章。

,您可以实现所需的行为,只需使用filter作为typeguard:

const children: Child[] = people.filter((p):p is Child => p.type === PersonType.child); // ok

更多有趣的例子,你可以在这里找到

最新更新