我很好奇TypeScript是否能在这个问题上帮我。
我的项目有文本消息、媒体消息、键盘消息和事件消息。
interface Message {
kind: 'text' // can be `text`, `media`, `keyboard` or `event`
}每种类型都有自己的属性,比如image就有预览。
目前我们所拥有的是这样的东西
export type MessageKind = 'text' | 'media' | 'keyboard' | 'event'export interface MessageSchema {
id: string // common to all messages
kind: MessageKind // common to all messages
room: string // common to all messages
// now come the specific fields and sadly all optionals.
filename?: string // specific of the "kind" media
caption?: string // specific of the "kind" media
mimetype?: string // specific of the "kind" media
orientation?: 'portrait' | 'landscape' // specific of the "kind" media
rows?: number // specific of the "kind" keyboard
columns?: number // specific of the "kind" keyboard
price?: number // specific of the "kind" event
balance?: number // specific of the "kind" event
charged?: boolean // specific of the "kind" event
}如何才能在不滥用可空类型的情况下设计出更好的解决方案?
发布于 2021-02-03 20:20:40
您可以对公共字段使用交叉点类型,然后对所有种类特定的字段使用联合:
export type MessageSchema = {
id: string;
room: string;
} & (
| {
kind: "text";
}
| {
kind: "media";
filename: string;
caption: string;
mimetype: string;
orientation: "portrait" | "landscape";
}
| {
kind: "keyboard";
rows: number;
columns: number;
}
| {
kind: "event";
price: number;
balance: number;
charged: boolean;
}
);https://stackoverflow.com/questions/66027321
复制相似问题