Typescript interface, using string constants for properties

后端 未结 1 1533
感动是毒
感动是毒 2021-01-28 09:00

I recently encountered the following design-issue when trying to describe a Notification-format (and formats in general) with a Typescript interface.

Context: Notificati

相关标签:
1条回答
  • 2021-01-28 09:07

    You can use the Record<TKey, TValue> type to define the interface:

    type TextType = "Text"; // or "Message" if format changes later
    type TitleType = "Title";
    type PriorityType = "Priority";
    type Notification = Partial<Record<typeof TextType | typeof TitleType, string>
            & Record<typeof PriorityType, number>>;
    
    let notif: Notification;
    
    let t = notif[TextType] // Will be string
    let t2 = notif.Text // Also works 
    

    The problem is there is no compiler way to enforce that access happens using the string constant, you could still access with .

    Note

    On typescript 2.7 and newer you can also do:

    const TextType = "Text"; // or "Message" etc
    const TitleType = "Title";
    const PriorityType = "Priority";
    
    interface Notification {
        [TextType]?: string
        [TitleType]?: string
        [PriorityType]?: number
    }
    

    But the same problem still applies of access

    0 讨论(0)
提交回复
热议问题