我刚开始反应/打字,遇到了一个问题.我正在试图建立一个谷歌表单克隆。
我的想法是为每种类型的问题设置一个interface,如下所示:
interface ShortText {
question: string;
placeholder: string;
}
interface MultipleChoice {
question: string;
placeholder: string;
choices: string[];
}每种类型都是如此。接下来,我需要在我的存储中存储所有这些问题的列表(属于所有不同的接口)。但是,我不能这么做,因为它们都有不同的接口!
我怎么能这么做?
发布于 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
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":
...
}https://stackoverflow.com/questions/65469909
复制相似问题