【发布时间】:2018-07-14 11:15:32
【问题描述】:
我最近在尝试使用 Typescript 接口描述通知格式(以及一般格式)时遇到了以下设计问题。
上下文:通知在服务器(运行 javascript)和客户端(使用不同语言)之间交换(作为 JSON)。
我尝试过使用类似的接口
interface Notification
{
Text?: string,
Title?: string,
Priority?: number
}
但在我的场景中,我希望将属性绑定到字符串常量(从客户端源代码导出)
const kText = "Text";
const kTitle = "Title";
const kPriority = "Priority";
所以如果格式改变了,我们现在有了 kText = "Message",界面会自动变成
interface Notification
{
Message?: string,
Title?: string,
Priority?: number
}
理想情况下,所有的实例都像
notification.Text
应该仍然有效 - 基本上我希望将 Text 作为属性的别名,同时强制将 kText 作为其名称。有点像(根本不工作,但也许说明了我想要的):
type TextType = "Text"; // or "Message" if format changes later
type TitleType = "Title";
type PriorityType = "Priority";
interface Notification
{
[Text : TextType]?: string,
[Title : TitleType]?: string,
[Priority : PriorityType]?: number
}
有没有办法实现这样的目标?
如果没有,还有什么其他好的方法可以实现这一点?
【问题讨论】:
标签: javascript typescript interface