首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在反应式文本中处理父母一方下的不同类型

如何在反应式文本中处理父母一方下的不同类型
EN

Stack Overflow用户
提问于 2020-12-27 20:00:38
回答 1查看 37关注 0票数 0

我刚开始反应/打字,遇到了一个问题.我正在试图建立一个谷歌表单克隆。

我的想法是为每种类型的问题设置一个interface,如下所示:

代码语言:javascript
复制
interface ShortText {
    question: string;
    placeholder: string;
}

interface MultipleChoice {
    question: string;
    placeholder: string;
    choices: string[];
}

每种类型都是如此。接下来,我需要在我的存储中存储所有这些问题的列表(属于所有不同的接口)。但是,我不能这么做,因为它们都有不同的接口!

我怎么能这么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-27 20:16:38

联合类型可以在这里工作:https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types

例如,使用区分联合:https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#discriminating-unions

代码语言:javascript
复制
interface ShortText {
    kind: "shortText";
    question: string;
    placeholder: string;
}

interface MultipleChoice {
    kind: "multipleChoice";
    question: string;
    placeholder: string;
    choices: string[];
}

// Create a type which represents only one of the above types
// but you aren't sure which it is yet.
type Question =
  | ShortText
  | MultipleChoice;

...

let questions: Question[];

...

switch (question.kind) {
    case "shortText":
      ...
    case "multipleChoice":
      ...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65469909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档