首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用typescript类型系统改进我的代码

利用typescript类型系统改进我的代码
EN

Stack Overflow用户
提问于 2021-02-03 20:13:05
回答 1查看 35关注 0票数 0

我很好奇TypeScript是否能在这个问题上帮我。

我的项目有文本消息、媒体消息、键盘消息和事件消息。

代码语言:javascript
复制
interface Message {
  kind: 'text' // can be `text`, `media`, `keyboard` or `event` 
}

每种类型都有自己的属性,比如image就有预览。

目前我们所拥有的是这样的东西

代码语言:javascript
复制
export type MessageKind = 'text' | 'media' | 'keyboard' | 'event'
代码语言:javascript
复制
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
}

如何才能在不滥用可空类型的情况下设计出更好的解决方案?

EN

回答 1

Stack Overflow用户

发布于 2021-02-03 20:20:40

您可以对公共字段使用交叉点类型,然后对所有种类特定的字段使用联合:

代码语言:javascript
复制
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;
      }
);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66027321

复制
相关文章

相似问题

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