TypeScript 联合类型缺少属性

TypeScript Union Type missing properties

我有 3 种类型:

export type FooInitialStateType = {
  Id: string;
  Name: string;
  Email: string;
  Password: string
};

export type BarInitialStateType = {
  Id: string;
  Balance: number;
};

export type BazInitialStateType = {
  Id: string;
  Limit: number;
};

然后我创建一个联合类型,如下所示:

export type FooBarBazType = FooInitialStateType | BarInitialStateType | BazInitialStateType

然后我有一个通用方法来处理包含上述所有 3 种类型的数组:

  getFooBarBaz (
    events: FooBarBazType[]
  ): {
    foobarbaz0: FooBarBazType;
  } {
    const foobarbaz0 = <FooBarBazType>events[0];
    return {
      foobarbaz0
    };
  }

然后我从每个 class (foo, bar, baz):

调用这个泛型方法
    const {
      foobarbaz0
    }: {
      foobarbaz0: FooInitialStateType;
    } = this.getFooBarBaz(fooEvents);

我收到 TS 错误:

Type 'FooBarBazType' is not assignable to type 'FooInitialStateType'.

因为 FooInitialStateType 不包含 BarInitialStateTypeBazInitialStateType 的属性。

真题:

  1. 我如何利用泛型方法的联合类型来接受具有所有 3 种类型的数组,然后在我调用该方法的地方指定返回值应该是什么类型?

  2. 在这里使用联合类型是否正确?我有一种方法接受 3 种不同的类型,并生成一种类型。我需要调用函数知道并指定返回的 Type

您可能希望 getFooBarBaz() 成为一个 generic 函数,其中输出类型取决于输入类型:

function getFooBarBaz<T extends FooBarBazType>(events: T[]): { foobarbaz0: T; } {
    const foobarbaz0 = events[0];
    return {
        foobarbaz0
    };
}

那么它可能会按照您想要的方式运行:

const fooEvents = [
    {
        Id: "foo",
        Name: "Foobert",
        Email: "foobert@example.com",
        Password: "Emb4rr4ss|ngP455w%?d"
    }
];

const {
    foobarbaz0
}: {
    foobarbaz0: FooInitialStateType;
} = getFooBarBaz(fooEvents); // no error now

有帮助吗?祝你好运!

Playground link to code