首页 > 文章列表 > TypeScript字段如何支持多种数据类型?

TypeScript字段如何支持多种数据类型?

438 2025-03-16

在 typescript 中定义一个可以取多种类型的字段时,使用联合类型可能会导致错误。为了解决这个问题,我们可以使用内置的类型别名来创建一种新的类型,它包含所有可能的选项。

具体步骤如下:

首先,定义所有可能的类型:

interface itext {
  text: string;
}

interface iimage {
  width: number;
  height: number;
  size: number;
}

interface ifile {
  url: string;
  name: string;
}

然后,创建一个联合类型别名,该别名将所有类型组合成一个新的类型:

type alltypes = itext | iimage | ifile;

最后,使用联合类型别名来定义字段的类型:

interface Message {
  id: string;
  payload: AllTypes;
}

这样便创建了一个字段 payload,该字段可以接受 itext、iimage 或 ifile 类型。

来源:1740386976